【Lintcode】191. Maximum Product Subarray

記錄演算法發表於2020-11-30

題目地址:

https://www.lintcode.com/problem/maximum-product-subarray/description

給定一個長 n n n的陣列 A A A,求其最大乘積子陣列,返回那個最大乘積。

思路是動態規劃。設 f [ i ] f[i] f[i]是以 A [ i ] A[i] A[i]結尾的最大乘積子陣列的乘積,那麼如果 A [ i ] ≥ 0 A[i]\ge 0 A[i]0,則 f [ i ] = max ⁡ { A [ i ] , A [ i ] f [ i − 1 ] } f[i]=\max\{A[i],A[i]f[i-1]\} f[i]=max{A[i],A[i]f[i1]},但如果 A [ i ] < 0 A[i]< 0 A[i]<0,那麼 f [ i ] f[i] f[i]應該是或者就是 A [ i ] A[i] A[i]本身,或者由 A [ i ] A[i] A[i]乘以以 A [ i − 1 ] A[i-1] A[i1]為結尾的最小乘積子陣列的乘積得到,所以我們還需要開一個陣列 g g g g [ i ] g[i] g[i]存以 A [ i ] A[i] A[i]結尾的最小乘積子陣列的乘積。這樣就有 { f [ i ] = max ⁡ { A [ i ] , A [ i ] f [ i − 1 ] , A [ i ] g [ i − 1 ] } g [ i ] = min ⁡ { A [ i ] , A [ i ] f [ i − 1 ] , A [ i ] g [ i − 1 ] } \begin{cases}f[i]=\max\{A[i],A[i]f[i-1],A[i]g[i-1]\}\\g[i]=\min\{A[i],A[i]f[i-1],A[i]g[i-1]\}\end{cases} {f[i]=max{A[i],A[i]f[i1],A[i]g[i1]}g[i]=min{A[i],A[i]f[i1],A[i]g[i1]}初始條件 f [ 0 ] = g [ 0 ] = A [ 0 ] f[0]=g[0]=A[0] f[0]=g[0]=A[0],答案就是 f f f g g g所有數字的最大值。程式碼如下:

public class Solution {
    /**
     * @param nums: An array of integers
     * @return: An integer
     */
    public int maxProduct(int[] nums) {
        // write your code here
        int res = Integer.MIN_VALUE;
        int[] maxdp = new int[nums.length], mindp = new int[nums.length];
        maxdp[0] = mindp[0] = nums[0];
        res = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int a  = nums[i], b = nums[i] * maxdp[i - 1], c = nums[i] * mindp[i - 1];
            maxdp[i] = Math.max(a, Math.max(b, c));
            mindp[i] = Math.min(a, Math.min(b, c));
            
            res = Math.max(res, Math.max(maxdp[i], mindp[i]));
        }
        
        return res;
    }
}

時空複雜度 O ( n ) O(n) O(n)

相關文章