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.
乘法的一个符号改变,最大值可能变最小值,反之也可。所以这道题采用动态规划,层层递进,最后用一个maxALL来控制全局的最大量。AC码如下:
public class Solution {
public int maxProduct(int[] nums) {
int minLast = nums[0],maxLast=nums[0],minCur,maxCur;
int maxALL=nums[0];
for(int i=1;i<nums.length;i++){
maxCur = Math.max(nums[i],Math.max(maxLast*nums[i], minLast*nums[i]));
minCur = Math.min(nums[i], Math.min(maxLast*nums[i], minLast*nums[i]));
maxLast = maxCur;
minLast = minCur;
maxALL = Math.max(maxALL, maxCur);
}
return maxALL;
}
}