首页 > 其他 > 详细

LeetCode 152. Maximum Product Subarray

时间:2018-12-03 00:19:15      阅读:189      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!