Maximum Product Subarray

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

其实不用考虑太多情况,只需要比较dp最大 dp最小乘以当前值 和当前值比较就好了

时间复杂度 o(n).空间复杂度 o(n)

class Solution {
    public int maxProduct(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        
       int[] dpMax = new int[nums.length];
       int[] dpMin = new int[nums.length];
        
        dpMax[0] = nums[0];
        dpMin[0] = nums[0];
        
        int res = nums[0];
        
        for(int i = 1; i < nums.length ;i++){
            dpMax[i] = Math.max(Math.max(dpMax[i-1]*nums[i],dpMin[i-1]*nums[i]),nums[i]);
             dpMin[i] = Math.min(Math.min(dpMax[i-1]*nums[i],dpMin[i-1]*nums[i]),nums[i]);
               res = Math.max(dpMax[i],res);
        }
        
        
        return res;
    }
}

时间复杂度 o(n),空间复杂度 o(1)

找到最大乘积数组

Last updated