[leetcode 152] Maximum Product Subarray

来源:互联网 发布:项目管理协作软件 编辑:程序博客网 时间:2024/05/21 07:00

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;    }};


0 0
原创粉丝点击