152. Maximum Product Subarray & 1567. Maximum Length of Subarray With Positive Product

152. Maximum Product Subarrayarrow-up-right

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.

My Solutions:

和53题类似,但是加法累加结果只要是正的一定是递增,乘法中有可能现在看起来小的一个负数,后面跟另一个负数相乘就会得到最大的乘积。因此,需要在维护一个局部最大的同时,在维护一个局部最小,这样如果下一个元素遇到负数时,就有可能与这个最小相乘得到当前最大的乘积和

1. 当遍历到一个正数时,此时的max等于之前的max乘以这个正数或者当前正数中的较大值,此时的min等于之前的min*当前正数或者当前正数中的较小值。保证max和min的absolute value都是最大

2. 当遍历到一个负数时,用一个变量temp保存之前的最大值max。max等于之前min乘以这个负数或者当前负数中的较大值,min等于之前保存的最大值temp*当前负数或者当前负数中的较小值。

3. 在每遍历完一个数时,都要更新最终的最大值。

class Solution {
    public int maxProduct(int[] nums) {
        if (nums == null || nums.length <= 0) return 0;
        
        // 这里全部初始化为第一个数
        int max = nums[0], min = nums[0], res = nums[0]; 
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > 0) { 
                // 注意这里虽然此数是正数,还是要这样写。因为max/min有可能是0.
                max = Math.max(max * nums[i], nums[i]); 
                min = Math.min(min * nums[i], nums[i]);
            } else {
                int temp = max;
                max = Math.max(min * nums[i], nums[i]);
                min = Math.min(temp * nums[i], nums[i]);
            }
            res = Math.max(res, max);
        }
        return res;
    }
}

也可以写的很短

1567.Maximum Length of Subarray With Positive Product

Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.

A subarray of an array is a consecutive sequence of zero or more values taken out of that array.

Return the maximum length of a subarray with positive product.

Example 1:

Example 2:

My Solutions:

这道题求长度,因此用变量pos储存结果一定为正数的长度,neg储存结果一定是负数的长度。

Last updated