Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4]
,
the contiguous subarray [2,3]
has the largest product = 6
.
前面我们完成了和最大的子数组,现在是变成了乘积最大的子数组。
这里有一个难点就是如何应付负的元素呢?额外增加变量,标记相邻的乘积最小的子数组值
同样的,我们先考虑局部相邻的数组第 i 位的最大乘积子数组。
如果前面相邻的第 i - 1位的最大乘积子树组值为 curMax,乘积最小的子数组值为curMin
此时的第 i 位的取值有3种,curMax * nums[ i ], curMin * nums[ i ], nums[ i ]。
第 i 位的 curMax 为3者中最大的,curMin为3这者最小的。
最后将所有数组第 i 位的curMax 值 取max,就是最终的最大乘积值。
运行时间:
代码:
public class MaximumProductSubarray {
public int maxProduct(int[] nums) {
if (nums.length == 0) {
return 0;
}
int curMax = nums[0], curMin = nums[0], maxProduct = nums[0];
for (int i = 1; i < nums.length; i++) {
int temp = curMax;
curMax = Math.max(Math.max(nums[i] * curMin, nums[i] * curMax), nums[i]);
curMin = Math.min(Math.min(nums[i] * curMin, nums[i] * temp), nums[i]);
maxProduct = Math.max(curMax, maxProduct);
}
return maxProduct;
}
}