您的位置:首页 > 其它

[leetcode-152]Maximum Product Subarray(c)

2015-08-20 23:07 459 查看
问题描述:

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.

分析:这道题比较虐心,虽然和求最大子序列和很类似,但是要复杂很多。当我们从前向后遍历时,对于每个节点,我们希望取最大值,最大值的来源有三个,第一个是前一个节点的最大值与该点的乘机,第二个是前一个节点的最小值与该点的乘机。第三个就是该点自身的值。

代码如下:4ms

[code]int Min(int a,int b){
    return a<b?a:b;
}
int Max(int a,int b){
    return a>b?a:b;
}
int maxProduct(int* nums, int numsSize) {
   int min = nums[0];
   int max = nums[0];
   int res = nums[0];

   for(int i = 1;i<numsSize;i++){
       int maxmax = max*nums[i];
       int minmin = min*nums[i];

       max = Max(Max(maxmax,minmin),nums[i]);
       min = Min(Min(minmin,maxmax),nums[i]);
       res = Max(max,res);
   }
   return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: