《leetCode》:Maximum Product Subarray

来源:互联网 发布:painter for mac 中文 编辑:程序博客网 时间:2024/05/21 08:38

题目

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;}
1 0