Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest product. Example For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6.
Key Points: O(n) O(1)
- Same as Maximum Sum Subarray, the difference is the maximum product could be the result of two negative number. So you need to keep track of both maximum and minimum value from the last state and a global max value as the result.
public int maxProduct(int[] nums) {
if(nums.length==0){return 0;}
int len = nums.length;
int min,max,globalMax;
min = max = globalMax = nums[0];
for(int i=1; i<len; i++){
int curr = nums[i],
tempMax = Math.max(curr,Math.max(min*curr,max*curr)),
tempMin = Math.min(curr,Math.min(min*curr,max*curr));
min = tempMin;
max =tempMax;
globalMax =Math.max(globalMax,tempMax);
}
return globalMax;
}