[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:
    int maxProduct(int A[], int n) {
        if (n < 2) {
            return A[0];
        }
        int min_pro = A[0];
        int max_pro = A[0];
        int res = A[0];
        for (int i = 1; i < n; i++) {
            int tmp = min_pro;
            min_pro = min(min(A[i], A[i]*min_pro), max_pro*A[i]);
            max_pro = max(max(A[i], A[i]*max_pro), tmp*A[i]);
            res = max(res, max_pro);
        }
        return res;
    }
};


你可能感兴趣的:([LeetCode,刷题])