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

LeetCode 152. Maximum Product Subarray

时间:2018-12-03 00:49:56      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:nta   which   else   ==   size   The   ast   within   sub   

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.

class Solution {
public:
    const int inf = -9999999;
    int maxProduct(vector<int>& nums) {
        int ans = inf;
        vector<int> postive(nums.size()+1, inf);
        vector<int> negtive(nums.size()+1, inf);
        for(int i=0; i<nums.size(); i++){
            if( nums[i]<0){
                postive[i+1] = negtive[i] == inf ? inf : negtive[i] * nums[i];
                negtive[i+1] = postive[i] == inf ? nums[i] : min( nums[i], nums[i]*postive[i]);
            }else{
                postive[i+1] = postive[i] == inf ? nums[i] : max( nums[i], nums[i]*postive[i]);
                negtive[i+1] = negtive[i] == inf ? inf : negtive[i] * nums[i];
            }
            ans = max( ans ,max(postive[i+1], negtive[i+1]));
        }
        return ans;
    }
};

LeetCode 152. Maximum Product Subarray

标签:nta   which   else   ==   size   The   ast   within   sub   

原文地址:https://www.cnblogs.com/A-Little-Nut/p/10055781.html

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