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.
题意:找数组中乘积最大的连续子数组。
思路:maxLocal和minLocal分别代表到当前为止最大乘积和最小乘积,如果当前数字时正数,那么最大值在当前数字和它乘以maxLocal之中产生,否则在它和minLocal乘积中产生。
public int maxProduct(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int max = nums[0];
int maxLocal = nums[0];
int minLocal = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] < 0) {
int tmp = maxLocal;
maxLocal = minLocal;
minLocal = tmp;
}
maxLocal = Math.max(nums[i], maxLocal * nums[i]);
minLocal = Math.min(nums[i], minLocal * nums[i]);
max = Math.max(max, maxLocal);
}
return max;
}