码迷,mamicode.com
首页 > 其他好文 > 详细

152. Maximum Product Subarray

时间:2017-05-19 10:02:32      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:rom   lan   logs   ++   max   more   blog   href   value   

Problem statement:

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.

Solution:

It is similar with 53. Maximum Subarray. We should keep one more minimum product since the product of two negative number is a position number. The current max and min value should choose from three candidates, nums[i], cur_max * nums[i] and cur_min * nums[i].

Time complexity is O(n).

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        if(nums.empty()){
            return 0;
        }
        int cur_max = 0;
        int cur_min = 0;
        int pre_max = nums[0];
        int pre_min = nums[0];
        int tot_max = nums[0];
        for(int i = 1; i < nums.size(); i++){
            cur_max = max(nums[i], max(pre_max * nums[i], pre_min * nums[i]));
            cur_min = min(nums[i], min(pre_max * nums[i], pre_min * nums[i]));
            pre_max = cur_max;
            pre_min = cur_min;
            tot_max = max(tot_max, cur_max);
        }
        return tot_max;
    }
};

 

152. Maximum Product Subarray

标签:rom   lan   logs   ++   max   more   blog   href   value   

原文地址:http://www.cnblogs.com/wdw828/p/6876426.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!