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
1 public int maxProduct(int[] nums) { 2 // initialize 3 int[] max = new int[nums.length]; 4 int[] min = new int[nums.length]; 5 max[0] = nums[0]; 6 min[0] = nums[0]; 7 int result = nums[0]; 8 // max[i]: max product of ith item 9 // min[i]: min product of ith item 10 for(int i = 1; i < nums.length; i++){ 11 max[i] = Math.max(Math.max(max[i-1] * nums[i] , min[i-1]*nums[i]), nums[i]); 12 min[i] = Math.min(Math.min(max[i-1] * nums[i] , min[i-1]*nums[i]), nums[i]); 13 result = Math.max(result, max[i]); 14 } 15 return result; 16 }