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
.
solution implement by java:
解答思路:每次选择一个元素都是如果该元素使得乘积变大则加入,否则不乘,所以我们需要两个变量分别用来记录在决定当前元素是否需要乘的时候,前面子串所得到的最小值和最大值,每次乘积结果都再用一个变量来存取记录,最后走完整个过程,记录下来的最大值就是结果。
public int maxProduct(int[] nums) {
if(nums.length==1)
return nums[0];
int left=nums[0];
int right=nums[0];
int maxpro=nums[0];
int max,min;
for(int i=1;i<nums.length;++i){
max=Math.max(Math.max(left*nums[i],right*nums[i]),nums[i]);
min=Math.min(Math.min(left*nums[i],right*nums[i]),nums[i]);
maxpro=Math.max(max,maxpro);
left=max;
right=min;
}
return maxpro;
}