首页 > 代码库 > LeetCode Maximum Product Subarray

LeetCode Maximum Product Subarray

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.

思路分析:这题与LeetCode Maximum Subarray类似,只是要注意两个负数的乘积可能变成一个很大的正数,因此要同时维护maxLocal和minLocal以及maxGlobal,初值为A[0],之后从A[1]开始遍历,maxLocal取A[i],A[i]*maxLocal.A[i]*minLocal中的最大,minLocal取A[i],A[i]*maxLocal.A[i]*minLocal中的最小,maxGlobal则是始终保存maxLocal中的最大值。要注意,更新minLocal时要用到原始的maxLocal的拷贝,而不是更新之后的值。

AC Code:

public class Solution {
    public int maxProduct(int[] A) {
        //01:42
        if(A.length == 0) return 0;
        if(A.length == 1) return A[0];
        
        int maxLocal =  A[0];
        int minLocal = A[0];
        int maxGlobal = A[0];
        
        for(int i = 1; i < A.length; i++){
            int maxCopy = maxLocal;
            maxLocal = Math.max(Math.max(A[i], A[i] * maxLocal), A[i] * minLocal);
            minLocal = Math.min(Math.min(A[i], A[i] * maxCopy), A[i] * minLocal);
            maxGlobal = Math.max(maxGlobal, maxLocal);
        }
        return maxGlobal;
        //01:47
    }
}


LeetCode Maximum Product Subarray