Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4]
,
the contiguous subarray [2,3]
has the largest product = 6
.
We need to keep a local max and a local min, because the local min may become local max if it is multiplied by a negative number. We also need to keep a global max variable to represent the current global max.
public class Solution {
public int maxProduct(int[] nums) {
if (nums == null || nums.length == 0)
return Integer.MIN_VALUE;
int max_local = nums[0];
int min_local = nums[0];
int max_global = nums[0];
for (int i = 1; i < nums.length; i++) {
int max_copy = max_local;
max_local = Math.max(Math.max(nums[i], nums[i] * max_local), min_local * nums[i]);
min_local = Math.min(Math.min(nums[i], nums[i] * max_copy), min_local * nums[i]);
max_global = Math.max(max_local, max_global);
}
return max_global;
}
}