x 6. 152. Maximum Product Subarray

152. Maximum Product SubarrayMedium16.4K503Companies

Given an integer array nums, find a

subarray that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= nums.length <= 2 * 104

  • -10 <= nums[i] <= 10

  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

2nd Try

time: O(N)

space: O(1)

/**
 * @param {number[]} nums
 * @return {number}
 */

var maxProduct = function(nums) {
    let max = nums[0];
    let minMax = nums[0];
    let maxMax = nums[0];

    for (let i = 1; i < nums.length; i++) {
        const curr = nums[i];

        if (curr < 0) {
            const temp = minMax;
            minMax = maxMax;
            maxMax = temp;
        }

        minMax = Math.min(curr, minMax * curr);
        
        maxMax = Math.max(curr, maxMax * curr);
        max = Math.max(maxMax, max);
    }

    return max;
};

1st try

/**
 * @param {number[]} nums
 * @return {number}
 */

let max;
var maxProduct = function(nums) {
    max = {};
    calcLocal(nums, 0, nums.length - 1);
    return max.val;
};

function calcLocal(nums, lo, hi) {
    if (lo === hi) {
        return nums[lo];
    }

    const m = lo + Math.floor((hi - lo) / 2);
    const left = calcLocal(nums, lo, m); // { left, right, total}
    const right = calcLocal(nums, m + 1, hi); // { left, right, total}
    const product = calcProduct();

    // left.right * right.left, total * total

    return { left, right, total}
}

Last updated