Tutorialspoint
Problem
Solution
Submissions

Maximum Product Subarray

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to find the maximum product of a contiguous subarray within a one-dimensional array of numbers. The array contains both positive and negative integers. You need to find the subarray with the largest product.

Example 1
  • Input: nums = [2, 3, -2, 4]
  • Output: 6
  • Explanation:
    • All possible subarrays are [2], [3], [-2], [4], [2,3], [3,-2], [-2,4], [2,3,-2], [3,-2,4], [2,3,-2,4].
    • Their products are 2, 3, -2, 4, 6, -6, -8, -12, -24, -48.
    • The subarray [2,3] has the maximum product of 6.
    • Therefore, the maximum product is 6.
Example 2
  • Input: nums = [-2, 0, -1]
  • Output: 0
  • Explanation:
    • All possible subarrays include [0] which has product 0.
    • Other subarrays like [-2], [-1], [-2,0], [0,-1], [-2,0,-1] have products -2, -1, 0, 0, 0.
    • The maximum product among all is 0.
    • Therefore, the result is 0.
Constraints
  • 1 ≤ nums.length ≤ 2 × 10^4
  • -10 ≤ nums[i] ≤ 10
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysGoldman SachsTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Keep track of both maximum and minimum product ending at each position
  • For each element, calculate new max and min considering current element
  • Handle negative numbers by swapping max and min when current number is negative
  • Update the global maximum product at each step
  • Consider the case where current element itself might be the maximum product

Steps to solve by this approach:

 Step 1: Initialize maxSoFar, maxEndingHere, and minEndingHere with the first element
 Step 2: Iterate through the array starting from the second element
 Step 3: If current element is negative, swap maxEndingHere and minEndingHere
 Step 4: Update maxEndingHere as maximum of current element or product with previous max
 Step 5: Update minEndingHere as minimum of current element or product with previous min
 Step 6: Update maxSoFar with the maximum of current maxSoFar and maxEndingHere
 Step 7: Return the final maxSoFar as the result

Submitted Code :