LeetCode 152. Maximum Product Subarray

Posted A-Little-Nut

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 152. Maximum Product Subarray相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode152. Maximum Product Subarray

[leetcode-152-Maximum Product Subarray]

leetcode152. Maximum Product Subarray

LeetCode-152-Maximum Product Subarray

[动态规划] leetcode 152 Maximum Product Subarray

leetcode 152. Maximum Product Subarray --------- java