Maximum Product Subarray - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

Goal

Given an integer array nums, find the contiguous subarray with the largest product and return that product.

Key Idea (Intuition)

For a subarray that ends at index i, any candidate product must arise from either extending a previously tracked sequence or starting fresh at nums[i]. We therefore maintain two running values for subarrays ending at the current index:

  • maxProduct — maximum product ending at the current index
  • minProduct — minimum product ending at the current index

When nums[i] < 0, multiplying by a negative reverses order: among the two extension options we must compare, minProduct × nums[i] is greater than or equal to maxProduct × nums[i]. This reversal between the extension candidates is precisely why we maintain both the running maxProduct and minProduct at every step.

Initialization

  • maxProduct = nums[0]
  • minProduct = nums[0]
  • result = nums[0] (global best so far)
  • Start traversal at i = 1.

Traversal

For each index i from 1 to n - 1:

  1. Form candidates for subarrays ending at i: c1 = maxProduct × nums[i], c2 = minProduct × nums[i], c3 = nums[i].
  2. Update per-index extremes: maxProduct = max(c1, c2, c3); minProduct = min(c1, c2, c3).
  3. Update global best: result = max(result, maxProduct).

Return

Return result as the maximum product of any contiguous subarray.

Time Complexity

The algorithm makes a single pass through the array of length n. At each index, it performs a constant amount of work: computing two products and updating maxProduct, minProduct, and result. Therefore, the time complexity is O(n).

Space Complexity

The algorithm uses only a constant amount of extra space for variables such as maxProduct, minProduct, result, and index. No additional data structures that grow with input size are required. Therefore, the space complexity is O(1).

Visucodize editorial solution titled JS Solution for LeetCode's Maximum Product Subarray coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/maximum-product-subarray.