152. 乘积最大子数组
难度:中等
给你一个整数数组 nums
,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
解答:
class Solution {
//动态规划
//时间复杂度O(N)。空间复杂度O(1)
public int maxProduct(int[] nums) {
int n = nums.length;
if(n == 0) return 0;
else if(n == 1) return nums[0];
int ans = nums[0], imin = nums[0], imax = nums[0];
for(int i = 1; i < n; i++){
int a = imax * nums[i];
int b = imin * nums[i];
imax = Math.max(Math.max(a, nums[i]), b);
imin = Math.min(Math.min(a, nums[i]), b);
ans = Math.max(imax, ans);
}
return ans;
}
}
参考自:
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/maximum-product-subarray/solution/cheng-ji-zui-da-zi-shu-zu-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。