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
.
Subscribe to see which companies asked this question
按0分成几段 每段最大值在这几个之间出 1.全乘起来 2.第一个负数及之前的除外 剩下的全乘起来 3.最后一个负数及之后的除外,剩下的全乘起来 然后再所有这些值里取最大的
public class Solution {
public int maxProduct(int[] nums) {
int ret = Integer.MIN_VALUE;
if(nums.length==1)return nums[0];
ret = nums[0];
int i = 0;
while(i<nums.length){
int cheng1 = 1;
int cheng2 = 1;
int start = 0;//第一个负数之后开始乘
while(i<nums.length&&nums[i]!=0){
cheng1*=nums[i];
if(start==1)cheng2*=nums[i];
if(cheng1>ret)ret = cheng1;
if(start==1&&cheng2>ret)ret=cheng2;
if(nums[i]<0)start=1;
i++;
}
if(i<nums.length&&nums[i]==0&&ret<0)ret=0;
i++;
}
return ret;
}
}