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.
题意:
求最大乘积子数组
思路:
1. the sign(I mean, if it is positive or negative) influence the product value
2. when iterating each item, it can be postive or negative
3. we use max[i] to stand for max product of ith item
4. we use min[i] to stand for min product of ith item
5. so function rule:
max[i]: max(max[i -1]*nums[i], min[i-1]* nums[i], nums[i])
min[i]: min(max[i -1]*nums[i], min[i-1]* nums[i], nums[i])
code
public int maxProduct(int[] nums) {
// initialize
int[] max = new int[nums.length];
int[] min = new int[nums.length];
max[0] = nums[0];
min[0] = nums[0];
int result = nums[0];
// max[i]: max product of ith item
// min[i]: min product of ith item
for(int i = 1; i < nums.length; i++){
max[i] = Math.max(Math.max(max[i-1] * nums[i] , min[i-1]*nums[i]), nums[i]);
min[i] = Math.min(Math.min(max[i-1] * nums[i] , min[i-1]*nums[i]), nums[i]);
result = Math.max(result, max[i]);
}
return result;
}