152 Leetcode Solution using JavaScript

Maximum Product Subarray Solution Explained

·

2 min read

Let's first look at the problem statement:

Given an integer array nums, find a subarray the product. The test cases are generated so that the answer will fit in a 32-bit integer.

This requires us to find the contiguous subarray with the maximum product of its elements.

Some examples:

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

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

A simple solution is to iterate through all possible subarrays and calculate the product, keeping track of the maximum product.


function maxProduct(nums) {
  let max = Number.MIN_SAFE_INTEGER;

  for (let i = 0; i < nums.length; i++) {
    let product = 1;
    for (let j = i; j < nums.length; j++) {
       product *= nums[j];  
       max = Math.max(max, product);
    }
  }

  return max;
}

This generates all subarrays starting from index i and ending at j and calculates the product.

Time Complexity - O(N^2) since we have nested loops Space Complexity - O(1)

While simple, this is inefficient for large inputs. We can optimize it by keeping track of current max and min product ending at each index.

Optimal Solution

function maxProduct(nums) {

  let max = nums[0], min = nums[0], result = nums[0];

  for (let i = 1; i < nums.length; i++) {

    let curr = nums[i];
    let tempMax = Math.max(curr, max * curr, min * curr);

    min = Math.min(curr, max * curr, min * curr);  

    max = tempMax;

    result = Math.max(max, result);
  }

  return result; 
}

The key points are:

  • Maintain both current maximum and minimum product ending at index i.

  • Calculate next max and min product using curr, maxcurr, and mincurr.

  • This handles both positive and negative cases.

  • Update the global result.

We optimize to O(N) time and O(1) space.

Summary

This problem demonstrates how dynamic programming can optimize brute force solutions by maintaining state. The optimal approach achieves the maximum product subarray in linear time.