Thursday, February 12, 2015

Maximum Product Subarray -- leetcode

Question:
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.
Answer:
DP method:
maxp(i) = max(max(maxp(i-1) * A[i], minp(i-1) * A[i] ), A[i]);
minp(i) = min(min(minp(i-1) *A[i], minp(i-1) * A[i]), A[i]);
res = max(maxp(i)) for all i.
class Solution {
public:
    int maxProduct(int A[], int n) {
        int res = A[0];
        int maxp = A[0];
        int minp = A[0];

        for (int i=1;i<n;i++){
            int tmpmax = maxp;
            int tmpmin = minp;
            maxp = max(max(tmpmax*A[i],tmpmin*A[i]),A[i]);
            minp = min(min(tmpmax*A[i],tmpmin*A[i]),A[i]);
            res = max(maxp,res);
        }
        return res;
    }
};

No comments:

Post a Comment