152. Maximum Product Subarray

来源:互联网 发布:金牌网吧奖励软件 编辑:程序博客网 时间:2024/06/14 00:10

Description:

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.


Solution:

int maxProduct(int A[], int n) {    // store the result that is the max we have found so far    int r = A[0];    // imax/imin stores the max/min product of    // subarray that ends with the current number A[i]    for (int i = 1, imax = r, imin = r; i < n; i++) {        // multiplied by a negative makes big number smaller, small number bigger        // so we redefine the extremums by swapping them        if (A[i] < 0)            swap(imax, imin);        // max/min product for the current number is either the current number itself        // or the max/min by the previous number times the current one        imax = max(A[i], imax * A[i]);        imin = min(A[i], imin * A[i]);        // the newly computed max value is a candidate for our global result        r = max(r, imax);    }    return r;}
class Solution {public:    int maxProduct(int A[], int n) {        int frontProduct = 1;        int backProduct = 1;        int ans = INT_MIN;        for (int i = 0; i < n; ++i) {            frontProduct *= A[i];            backProduct *= A[n - i - 1];            ans = max(ans,max(frontProduct,backProduct));            frontProduct = frontProduct == 0 ? 1 : frontProduct;            backProduct = backProduct == 0 ? 1 : backProduct;        }        return ans;    }};

Summary:
自己写的时候花太多时间使用各种条件逻辑在负数与0的处理上了,没有抓住问题的本质。学习了大佬们的代码和算法,收获颇多。
路漫漫其修远兮,吾将上下而求索。

原创粉丝点击