Maximum Product Subarray
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.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) {
if(nums == null || nums.length == 0)
return 0;
int[] dpMax = new int[nums.length];
int[] dpMin = new int[nums.length];
dpMax[0] = nums[0];
dpMin[0] = nums[0];
int res = nums[0];
for(int i = 1; i < nums.length ;i++){
dpMax[i] = Math.max(Math.max(dpMax[i-1]*nums[i],dpMin[i-1]*nums[i]),nums[i]);
dpMin[i] = Math.min(Math.min(dpMax[i-1]*nums[i],dpMin[i-1]*nums[i]),nums[i]);
res = Math.max(dpMax[i],res);
}
return res;
}
}Last updated