Problem Description:
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.
Analysis:
本题的思路就是保存每一步中的当前最小和最大的值,然后获取最终的最大和最小值,保留最小值是需要考虑到负数相乘可能会获取得到最大的值。代码如下:
Code:
class Solution {
public int maxProduct(int[] nums) {
if(nums.length < 1)
return 0;
int maxValue = nums[0];
int curMax = nums[0];
int curMin = nums[0];
for(int i = 1; i < nums.length; i++) {
int temp = curMax;
curMax = Math.max(Math.max(nums[i], nums[i] * curMax), curMin * nums[i]);
curMin = Math.min(Math.min(nums[i], nums[i] * curMin), temp * nums[i]);
maxValue = Math.max(maxValue, curMax);
}
return maxValue;
}
}