Leetcode Maximum Product Subarray

来源:互联网 发布:成都市网络理政平台app 编辑:程序博客网 时间:2024/05/21 07:02

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.

使用DP


class Solution {

public:
    int maxProduct(int A[], int n) {
        if (n == 1) return A[0];
        int pMax=A[0],nMax=A[0],m=A[0];
        
        for(int i = 1; i < n; i++)
        {
            if(A[i]<0) swap(pMax,nMax);
            pMax=max(pMax*A[i],A[i]);
            nMax=min(nMax*A[i],A[i]);
            m = max(pMax,m);
        }
        return m;
    }
};
0 0
原创粉丝点击