Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
这题跟“最大连续子序列和”非常类似,只不过变成了“最大连续子序列积”,所以解决 思路也很类似。
仅仅有一个小细节需要注意,就是负负得正,两个负数的乘积是正数,因此我们不 仅要跟踪最大值,还要跟踪最小值
class Solution {
public int maxProduct(int[] nums) {
int maxLocal = nums[0];
int minLocal = nums[0];
int maxGlobal = nums[0];
for (int i = 1; i < nums.length; i++) {
int temp = maxLocal;
maxLocal = Math.max(nums[i], Math.max(nums[i] * maxLocal, nums[i] * minLocal));
minLocal = Math.min(nums[i], Math.min(nums[i] * temp, nums[i] * minLocal));
maxGlobal = Math.max(maxLocal, maxGlobal);
}
return maxGlobal;
}
}