LC 152 Maximum Product Subarray(M)

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.

public int maxProduct(int[] nums)

边界判断 如果数组没有值,直接返回0

解体思路 DP 累计乘,因为存在负负的正的情况,要同时保留最大,和最小, 关于数组起点,是比较如果 当前n值比 n-1的最大累计还大,或比 n-1最小累计还小 则 以n为起点重新累计。

public int maxProduct(int[] nums) {
    if (nums.length<1)
        return 0;
    int maxTotal = nums[0];
    int curMax = nums[0];
    int curMin = nums[0];
    for(int i = 1; i < nums.length; i++){
        int temp = curMax;
        curMax = Math.max(Math.max(curMax * nums[i], curMin * nums[i]), nums[i]);
        curMin = Math.min(Math.min(temp * nums[i], curMin * nums[i]), nums[i]);
        maxTotal = Math.max(maxTotal, curMax);
    }
    return maxTotal;
}

Last updated

Was this helpful?