【Lintcode】191. Maximum Product Subarray

题目地址:

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)

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页