152. Maximum Product Subarray - LeetCode

Question

152. Maximum Product Subarray java

Solution

題目大意:求數列中連續子序列的最大連乘積c++

思路:動態規劃實現,如今動態規劃理解的還不透,照着公式往上套的,這個問題要注意正負,須要維護兩個結果app

Java實現:code

public int maxProduct(int[] nums) {
    if (nums.length == 1) return nums[0];

    // 定義問題:狀態及對狀態的定義
    // 設max[i]表示數列中第i項結尾的連續子序列的最大連乘積
    // 求max[0]...max[n]中的最大值
    // 狀態轉移方程
    // max[0] = nums[0]
    // max[i] = Max.max(max[i-1] * nums[i], nums[i])
    int[] max = new int[nums.length];
    int[] min = new int[nums.length];
    for (int i = 0; i < nums.length; i++) {
        max[i] = min[i] = nums[i];
    }

    int product = nums[0];
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] < 0) {
            max[i] = Math.max(min[i - 1] * nums[i], max[i]);
            min[i] = Math.min(max[i - 1] * nums[i], min[i]);
            product = Math.max(max[i], product);
        } else {
            max[i] = Math.max(max[i - 1] * nums[i], max[i]);
            min[i] = Math.min(min[i - 1] * nums[i], min[i]);
            product = Math.max(max[i], product);
        }
    }
    return product;
}

別人的實現ip

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

關於動態規劃

Ref

什麼是動態規劃?動態規劃的意義是什麼 - 知乎提問leetcode

相關文章
相關標籤/搜索