您的位置:首页 > 其它

《leetCode》:Maximum Product Subarray

2016-03-17 21:31 239 查看

题目

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.


思路

算法:最大产品值主要由两个因素决定:第一为 0元素,第二为负数的个数

当在遍历的过程中,遇到了 0元素,则采用以下的决策

1)如果此时的值为负数,则lowpoint逐渐向highpoint靠拢,使得当前值为正数

2)如果此时的值为正数,则抛弃掉此时的值,lowpoint跳过这个0元素的位置指向第一个非零值 ,继续运算判断

还有:在遍历完整个数组之后,如果当前值为负数,也要lowpoint逐渐向highpoint靠拢,使得当前值为正数

在上面的过程中,总要不断的更新最大值

实现代码如下:

int max(int a,int b){
return a>b?a:b;
}
int maxProduct(int* nums, int numsSize) {
if(nums==NULL||numsSize<1){
return 0;
}
if(numsSize==1){
return nums[0];
}
//用双指针来进行
int lowpoint=0;
int highpoint=0;
int maxValue=INT_MIN;
int curValue=1;
while(highpoint<numsSize){
if(nums[highpoint]==0&&curValue<0&&lowpoint<highpoint-1){
for(;curValue<0&&lowpoint<highpoint-1;lowpoint++){//直到curValue为正
curValue/=nums[lowpoint];
maxValue=max(maxValue,curValue);
}

}
else if(nums[highpoint]==0){
maxValue=max(maxValue,0);//注意
highpoint++;
lowpoint=highpoint;
curValue=1;
}
else{
curValue*=nums[highpoint++];
maxValue=max(maxValue,curValue);
}
}
for(;curValue<0&&lowpoint<numsSize-1;lowpoint++){//当curValue小于零时,则增大lowpoint
curValue/=nums[lowpoint];
maxValue=max(maxValue,curValue);
}
return maxValue;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: