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
.
解题思路:
计算连续的积最大,由于会有负数出现,因此需要用两个int表示包含nums[i]的最大值和最小值,然后res=Math.max(res, max)即可,JAVA实现如下:
public int maxProduct(int[] nums) {
if(nums.length==1)
return nums[0];
int max=nums[0],min=nums[0],res=nums[0],maxTemp=0,mintemp=0;
for(int i=1;i<nums.length;i++){
maxTemp=max*nums[i];
mintemp=min*nums[i];
max=Math.max(nums[i],Math.max(maxTemp, mintemp));
min=Math.min(nums[i],Math.min(maxTemp, mintemp));
res=Math.max(res, max);
}
return res;
}