Bird
Raised Fist0
DSA Javascriptprogramming~15 mins

Maximum Product Subarray in DSA Javascript - Deep Dive

Choose your learning style10 modes available
Overview - Maximum Product Subarray
What is it?
Maximum Product Subarray is a problem where you find the contiguous part of an array that has the largest product of its elements. The array can contain positive, negative numbers, and zeros. The goal is to find the highest product you can get by multiplying numbers next to each other in the array.
Why it matters
This problem helps us understand how to handle arrays with both positive and negative numbers when looking for maximum results. Without this concept, we might miss the best solution because negative numbers can flip the product sign, and zeros can reset the product. It teaches careful tracking of values and is useful in financial calculations, signal processing, and other fields where products matter.
Where it fits
Before this, you should know basic array operations and understand how to find maximum or minimum values in a list. After this, you can learn more complex dynamic programming problems and sliding window techniques that handle subarray problems efficiently.
Mental Model
Core Idea
Track both the maximum and minimum products at each step because a negative number can turn a small minimum product into a large maximum product.
Think of it like...
Imagine walking on a path where stepping on a slippery stone (negative number) can flip your direction. You must remember both your furthest forward and backward steps to know how far you can go overall.
Array: [2, -3, 4, -1, 0, -2, 3]

At each step:
Index:  0    1     2     3     4    5    6
Value: [2,  -3,    4,   -1,    0,  -2,   3]
MaxP:  [2,  -3,   12,   12,    0,   0,   3]
MinP:  [2,  -3,   -3,  -48,    0,  -2,  -6]

Max product so far: 12
Build-Up - 7 Steps
1
FoundationUnderstanding the Problem Setup
🤔
Concept: Learn what a subarray is and what it means to find the maximum product of a subarray.
A subarray is a continuous part of an array. For example, in [1, 2, 3], subarrays include [1], [2], [3], [1, 2], [2, 3], and [1, 2, 3]. The maximum product subarray is the one whose elements multiply to the largest number. For example, in [2, 3, -2, 4], the maximum product subarray is [2, 3] with product 6.
Result
You understand what subarrays are and what it means to find the maximum product among them.
Knowing what a subarray is helps you focus on continuous parts of the array, which is key to solving this problem.
2
FoundationSimple Maximum Product Without Negatives
🤔
Concept: Find the maximum product subarray when all numbers are positive.
If all numbers are positive, the maximum product subarray is the entire array because multiplying more positive numbers only increases the product. For example, in [1, 2, 3, 4], the product of the whole array is 24, which is the maximum.
Result
You see that with only positive numbers, the problem is straightforward: the whole array is the answer.
Understanding this simple case sets a baseline before handling negatives and zeros, which complicate the problem.
3
IntermediateHandling Negative Numbers Carefully
🤔Before reading on: do you think a negative number always lowers the product? Commit to yes or no.
Concept: Negative numbers can flip the sign of the product, so tracking only the maximum product is not enough.
When you multiply by a negative number, the maximum product can become minimum and the minimum product can become maximum. For example, if the max product so far is 6 and the min product is -2, multiplying by -3 flips them: max becomes -6 and min becomes -18. So, you must track both max and min products at each step.
Result
You learn to keep two values at each step: max product and min product, to handle sign flips caused by negatives.
Tracking both max and min products prevents missing large products that come from multiplying two negatives.
4
IntermediateResetting on Zero Values
🤔Before reading on: do you think zeros help or hurt the maximum product? Commit to your answer.
Concept: Zeros reset the product because multiplying by zero makes the product zero, so you must start fresh after zeros.
When you encounter zero, the product of any subarray including it is zero. So, you reset max and min products to the current number after zero to start a new subarray. For example, in [2, 3, 0, 4, -1], the max product subarray after zero starts fresh from 4.
Result
You understand that zeros break subarrays and require restarting the product tracking.
Recognizing zeros as reset points helps avoid incorrect product calculations that include zeros.
5
IntermediateDynamic Programming Approach
🤔Before reading on: do you think you can solve this by checking all subarrays or by updating values step-by-step? Commit to your answer.
Concept: Use dynamic programming to update max and min products at each index based on previous values.
At each index, calculate: - max product = max(current number, max product * current number, min product * current number) - min product = min(current number, max product * current number, min product * current number) Keep track of the global max product seen so far. This avoids checking all subarrays explicitly.
Result
You get an efficient O(n) solution that updates max and min products as you move through the array.
Dynamic programming reduces the problem from checking many subarrays to updating two values per step.
6
AdvancedImplementing Maximum Product Subarray in JavaScript
🤔Before reading on: do you think you can write code that tracks max and min products and handles zeros? Commit to your answer.
Concept: Write a complete JavaScript function that returns the maximum product subarray value.
function maxProduct(nums) { let maxProd = nums[0]; let minProd = nums[0]; let result = nums[0]; for (let i = 1; i < nums.length; i++) { let current = nums[i]; if (current < 0) { [maxProd, minProd] = [minProd, maxProd]; } maxProd = Math.max(current, maxProd * current); minProd = Math.min(current, minProd * current); result = Math.max(result, maxProd); } return result; } // Example: // Input: [2,3,-2,4] // Output: 6 // Explanation: Subarray [2,3] has the largest product 6.
Result
The function returns the correct maximum product for any input array, handling positives, negatives, and zeros.
Writing the code solidifies understanding of the logic and shows how to handle sign flips and resets efficiently.
7
ExpertOptimizing and Understanding Edge Cases
🤔Before reading on: do you think the algorithm handles single-element arrays and all negatives correctly? Commit to your answer.
Concept: Explore how the algorithm behaves with single elements, all negatives, and zeros, and optimize variable usage.
The algorithm works for single-element arrays by initializing maxProd, minProd, and result to the first element. For all negatives, it correctly tracks min and max products to find the maximum product subarray. For zeros, it resets tracking implicitly by comparing current number with products. You can optimize by using only variables without arrays for max and min products, reducing space complexity to O(1).
Result
The solution is robust for all edge cases and uses minimal memory.
Understanding edge cases prevents bugs in production and shows the power of careful variable management.
Under the Hood
The algorithm iterates through the array once, maintaining two variables: maxProd and minProd. maxProd stores the maximum product ending at the current index, and minProd stores the minimum product ending at the current index. When a negative number is encountered, maxProd and minProd swap because multiplying by a negative flips signs. At each step, maxProd and minProd are updated by comparing the current number alone and the product of the current number with previous maxProd or minProd. The global maximum is updated accordingly.
Why designed this way?
This approach was designed to avoid checking all subarrays, which would be slow (O(n^2)). Tracking both max and min products handles the sign flip caused by negatives efficiently. Alternatives like brute force were too slow, and simpler max-only tracking failed with negatives. This method balances speed and correctness.
Start
  ↓
Initialize maxProd, minProd, result = nums[0]
  ↓
For each number from index 1 to end:
  ├─ If number < 0: swap maxProd and minProd
  ├─ maxProd = max(number, maxProd * number)
  ├─ minProd = min(number, minProd * number)
  └─ result = max(result, maxProd)
  ↓
Return result
Myth Busters - 4 Common Misconceptions
Quick: Does the maximum product subarray always include the largest number? Commit to yes or no.
Common Belief:The maximum product subarray must include the largest number in the array.
Tap to reveal reality
Reality:The maximum product subarray may not include the largest number because negative numbers and zeros affect the product. Sometimes smaller numbers combined yield a larger product.
Why it matters:Assuming the largest number is always included can lead to wrong answers and missed maximum products.
Quick: Do you think tracking only the maximum product is enough? Commit to yes or no.
Common Belief:Tracking only the maximum product at each step is enough to solve the problem.
Tap to reveal reality
Reality:You must track both maximum and minimum products because a negative number can turn a minimum product into a maximum product.
Why it matters:Ignoring the minimum product causes missing large products that come from multiplying two negatives.
Quick: Does a zero always reduce the maximum product subarray? Commit to yes or no.
Common Belief:Zeros always reduce the maximum product subarray and should be avoided.
Tap to reveal reality
Reality:Zeros reset the product calculation, so they can separate subarrays. Sometimes the maximum product subarray is after a zero.
Why it matters:Misunderstanding zeros leads to incorrect product calculations and missed subarrays.
Quick: Can the maximum product subarray be empty? Commit to yes or no.
Common Belief:The maximum product subarray can be empty if all numbers are negative or zero.
Tap to reveal reality
Reality:The subarray must contain at least one element; it cannot be empty. The maximum product is at least the largest single element.
Why it matters:Thinking the subarray can be empty causes confusion and wrong implementations.
Expert Zone
1
Swapping max and min products only when the current number is negative is crucial to correctly handle sign flips.
2
The algorithm implicitly handles zeros without explicit resets by comparing the current number alone with products.
3
Tracking only two variables (maxProd and minProd) at each step achieves O(1) space complexity, which is optimal.
When NOT to use
This approach is not suitable if you need the actual subarray elements, not just the product value. In that case, you must track start and end indices. Also, if the array is extremely large and memory is limited, streaming algorithms or approximate methods might be better.
Production Patterns
In production, this algorithm is used in financial modeling to find periods of maximum growth or loss, in signal processing to detect strong signals, and in competitive programming as a classic dynamic programming example. It is often combined with tracking indices to return the subarray itself.
Connections
Kadane's Algorithm
Builds-on
Maximum Product Subarray extends Kadane's Algorithm for maximum sum subarray by handling multiplication and sign changes, deepening understanding of dynamic programming on arrays.
Sign Flipping in Mathematics
Same pattern
The need to track both max and min products mirrors how multiplying by negative numbers flips signs in math, showing how algebraic properties affect algorithm design.
Stock Market Analysis
Application
Finding maximum product subarrays relates to finding periods of maximum return in stock prices, connecting algorithmic thinking to real-world financial decisions.
Common Pitfalls
#1Not tracking minimum product leads to wrong results with negatives.
Wrong approach:function maxProduct(nums) { let maxProd = nums[0]; let result = nums[0]; for (let i = 1; i < nums.length; i++) { maxProd = Math.max(nums[i], maxProd * nums[i]); result = Math.max(result, maxProd); } return result; }
Correct approach:function maxProduct(nums) { let maxProd = nums[0]; let minProd = nums[0]; let result = nums[0]; for (let i = 1; i < nums.length; i++) { if (nums[i] < 0) { [maxProd, minProd] = [minProd, maxProd]; } maxProd = Math.max(nums[i], maxProd * nums[i]); minProd = Math.min(nums[i], minProd * nums[i]); result = Math.max(result, maxProd); } return result; }
Root cause:Assuming only the maximum product matters and ignoring how negatives flip signs.
#2Ignoring zeros causes incorrect product calculations.
Wrong approach:function maxProduct(nums) { let maxProd = 1; let result = Number.NEGATIVE_INFINITY; for (let num of nums) { maxProd *= num; result = Math.max(result, maxProd); } return result; }
Correct approach:function maxProduct(nums) { let maxProd = nums[0]; let minProd = nums[0]; let result = nums[0]; for (let i = 1; i < nums.length; i++) { if (nums[i] < 0) { [maxProd, minProd] = [minProd, maxProd]; } maxProd = Math.max(nums[i], maxProd * nums[i]); minProd = Math.min(nums[i], minProd * nums[i]); result = Math.max(result, maxProd); } return result; }
Root cause:Not resetting or handling zeros properly, leading to products stuck at zero or wrong values.
#3Assuming the maximum product subarray is always the entire array.
Wrong approach:function maxProduct(nums) { let product = 1; for (let num of nums) { product *= num; } return product; }
Correct approach:Use the dynamic programming approach tracking max and min products at each step to find the maximum product subarray.
Root cause:Over-simplifying the problem and ignoring subarray boundaries.
Key Takeaways
Maximum Product Subarray requires tracking both maximum and minimum products at each step to handle negative numbers correctly.
Zeros reset the product calculation and must be handled carefully to avoid incorrect results.
Dynamic programming allows solving this problem efficiently in one pass with O(n) time and O(1) space.
Understanding sign flips and resets is key to mastering this problem and similar array challenges.
Edge cases like single elements, all negatives, and zeros test the robustness of your solution.

Practice

(1/5)
1. What does the Maximum Product Subarray problem ask you to find in an array of integers?
easy
A. The subarray with the largest difference between elements
B. The contiguous subarray with the largest sum of its elements
C. The subarray with the smallest product of its elements
D. The contiguous subarray with the largest product of its elements

Solution

  1. Step 1: Understand the problem goal

    The problem asks for the contiguous subarray (elements next to each other) that has the maximum product when multiplied together.
  2. Step 2: Differentiate from sum problems

    This is different from maximum sum subarray problems because it focuses on multiplication, which can be affected by negative numbers and zeros.
  3. Final Answer:

    The contiguous subarray with the largest product of its elements -> Option D
  4. Quick Check:

    Maximum Product Subarray = largest product subarray [OK]
Hint: Look for the subarray with the highest multiplication result [OK]
Common Mistakes:
  • Confusing product with sum
  • Ignoring negative numbers impact
  • Thinking about non-contiguous subarrays
2. Which of the following JavaScript code snippets correctly initializes variables to track the maximum product subarray?
easy
A. let maxProd = Infinity, minProd = -Infinity, result = 0;
B. let maxProd = 0, minProd = 0, result = 0;
C. let maxProd = nums[0], minProd = nums[0], result = nums[0];
D. let maxProd = [], minProd = [], result = [];

Solution

  1. Step 1: Understand variable roles

    maxProd and minProd track the max and min products ending at current index; result stores the overall max product.
  2. Step 2: Correct initialization

    Initializing all three to the first element of the array ensures correct comparison and handling of negative numbers.
  3. Final Answer:

    let maxProd = nums[0], minProd = nums[0], result = nums[0]; -> Option C
  4. Quick Check:

    Initialize with first element for correct tracking [OK]
Hint: Start tracking with first element, not zero or arrays [OK]
Common Mistakes:
  • Initializing with zero causes wrong results if first element is negative
  • Using arrays instead of numbers for tracking
  • Using Infinity values incorrectly
3. What will be the output of the following JavaScript code?
const nums = [2, 3, -2, 4];
function maxProduct(nums) {
  let maxProd = nums[0], minProd = nums[0], result = nums[0];
  for (let i = 1; i < nums.length; i++) {
    if (nums[i] < 0) [maxProd, minProd] = [minProd, maxProd];
    maxProd = Math.max(nums[i], maxProd * nums[i]);
    minProd = Math.min(nums[i], minProd * nums[i]);
    result = Math.max(result, maxProd);
  }
  return result;
}
console.log(maxProduct(nums));
medium
A. 4
B. 6
C. -2
D. 8

Solution

  1. Step 1: Trace the loop and variable updates

    Start with maxProd=2, minProd=2, result=2.
    i=1 (3): maxProd=max(3,2*3)=6, minProd=min(3,2*3)=3, result=max(2,6)=6.
    i=2 (-2): nums[i]<0 so swap maxProd and minProd: maxProd=3, minProd=6.
    maxProd=max(-2,3*(-2))=max(-2,-6)=-2, minProd=min(-2,6*(-2))=min(-2,-12)=-12, result=max(6,-2)=6.
    i=3 (4): maxProd=max(4,-2*4)=4, minProd=min(4,-12*4)=-48, result=max(6,4)=6.
  2. Step 2: Determine final result

    The maximum product found is 6 from subarray [2,3].
  3. Final Answer:

    6 -> Option B
  4. Quick Check:

    Max product subarray = 6 [OK]
Hint: Swap max and min when negative to track products correctly [OK]
Common Mistakes:
  • Not swapping max and min on negative numbers
  • Confusing max product with sum
  • Incorrectly updating result
4. Identify the bug in the following code for Maximum Product Subarray and select the fix:
function maxProduct(nums) {
  let maxProd = 0, minProd = 0, result = 0;
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] < 0) [maxProd, minProd] = [minProd, maxProd];
    maxProd = Math.max(nums[i], maxProd * nums[i]);
    minProd = Math.min(nums[i], minProd * nums[i]);
    result = Math.max(result, maxProd);
  }
  return result;
}
medium
A. Initialize maxProd, minProd, and result with nums[0] instead of 0
B. Remove the swap of maxProd and minProd when nums[i] < 0
C. Start loop from i = 1 instead of 0
D. Use Math.min instead of Math.max for result update

Solution

  1. Step 1: Check variable initialization

    Initializing maxProd, minProd, and result to 0 causes wrong results if nums[0] is negative or non-zero. They should start at nums[0].
  2. Step 2: Confirm loop start and swap logic

    Loop starting at 0 is okay if initialization is correct. Swap on negative is needed to handle sign changes.
  3. Final Answer:

    Initialize maxProd, minProd, and result with nums[0] instead of 0 -> Option A
  4. Quick Check:

    Correct initialization fixes wrong product tracking [OK]
Hint: Always initialize tracking vars with first array element [OK]
Common Mistakes:
  • Starting loop at 0 with zero initialization
  • Removing swap logic on negative numbers
  • Updating result with min instead of max
5. Given the array nums = [1, -2, -3, 0, 7, -8, -2], what is the maximum product of any contiguous subarray?
hard
A. 112
B. 48
C. 7
D. 0

Solution

  1. Step 1: Trace subarrays and products

    Check subarrays:
    - [1] = 1
    - [1,-2] = -2
    - [1,-2,-3] = 6
    - [-2,-3] = 6
    - [7] = 7
    - [7,-8] = -56
    - [7,-8,-2] = 112 (max so far)
    Zero resets product.
    Other subarrays have smaller products.
  2. Step 2: Identify max product

    The maximum product is 112 from subarray [7, -8, -2].
  3. Final Answer:

    112 -> Option A
  4. Quick Check:

    Max product subarray = 112 [OK]
Hint: Consider negative pairs and zeros to find max product [OK]
Common Mistakes:
  • Ignoring zeros resetting product
  • Not considering negative number pairs
  • Only checking positive subarrays
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard