Bird
Raised Fist0
DSA Typescriptprogramming~15 mins

Maximum Product Subarray in DSA Typescript - 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 have positive, negative, and zero values. The goal is to find the subarray that, when multiplied together, gives the highest possible product.
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, making it tricky. It is useful in fields like finance or signal processing where products of sequences matter.
Where it fits
Before this, you should know about arrays and basic subarray problems like Maximum Sum Subarray. After this, you can learn about dynamic programming and more complex optimization problems.
Mental Model
Core Idea
Track both the maximum and minimum products ending at each position because a negative number can turn a minimum product into a maximum one.
Think of it like...
Imagine walking on a path where stepping on a slippery stone (negative number) can flip your direction. Sometimes slipping backward (minimum product) can help you jump forward farther later (maximum product).
Index:    0    1    2    3    4
Array:   [2,  -3,  -2,   4,  -1]
MaxProd: [2,  -3,  12,  48,  -1]
MinProd: [2,  -6,  -2,  -8,  -48]

At each step, max and min products update considering current number and previous max/min.
Build-Up - 7 Steps
1
FoundationUnderstanding Subarrays and Products
🤔
Concept: Learn what a subarray is and how to calculate the product of its elements.
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 product of a subarray is the multiplication of all its elements. For [2, 3], the product is 2 * 3 = 6.
Result
You can identify any subarray and compute its product by multiplying elements.
Understanding subarrays and their products is the base for solving maximum product subarray problems.
2
FoundationEffect of Negative and Zero Values
🤔
Concept: Learn how negative numbers and zeros affect the product of subarrays.
Multiplying by a negative number flips the sign of the product. For example, product of [2, -3] is -6. Multiplying by zero resets the product to zero. This means subarrays with negatives and zeros behave differently than only positive numbers.
Result
You see that negative numbers can turn a small product into a large one if multiplied again by a negative number.
Recognizing how negatives and zeros change products is key to tracking max and min products.
3
IntermediateTracking Maximum and Minimum Products
🤔Before reading on: do you think tracking only the maximum product so far is enough to solve this problem? Commit to yes or no.
Concept: Keep track of both the maximum and minimum product ending at each index to handle sign flips caused by negatives.
At each element, calculate: - max product ending here = max(current number, max product * current number, min product * current number) - min product ending here = min(current number, max product * current number, min product * current number) This way, if the current number is negative, the min product can become max and vice versa.
Result
You can correctly find the maximum product subarray even with negatives and zeros.
Tracking both max and min products prevents missing cases where negatives flip the product sign.
4
IntermediateDynamic Programming Approach
🤔Before reading on: do you think this problem can be solved efficiently without checking all subarrays? Commit to yes or no.
Concept: Use dynamic programming to update max and min products at each step, avoiding checking all subarrays explicitly.
Instead of checking every subarray (which is slow), update max and min products as you move through the array. Keep a global max product to track the best answer so far. This reduces time complexity from O(n^2) to O(n).
Result
The solution runs efficiently even for large arrays.
Dynamic programming transforms a slow brute force problem into a fast linear-time solution.
5
IntermediateHandling Edge Cases: Zeros and Single Elements
🤔
Concept: Learn how zeros reset products and how single elements can be the max product subarray.
When the current number is zero, max and min products reset to zero or the current number. Also, sometimes the max product subarray is just one element, especially if all others are negative or zero.
Result
The algorithm correctly handles zeros and single-element subarrays.
Considering zeros and single elements ensures the solution works for all input types.
6
AdvancedImplementing Maximum Product Subarray in TypeScript
🤔Before reading on: do you think the code needs to store all max/min products or just the last ones? Commit to your answer.
Concept: Implement the algorithm efficiently using variables to track only the last max and min products and the global max product.
```typescript function maxProduct(nums: number[]): number { let maxProd = nums[0]; let minProd = nums[0]; let result = nums[0]; for (let i = 1; i < nums.length; i++) { const 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; } ``` This code swaps max and min when current is negative, then updates them and the result.
Result
The function returns the maximum product of any subarray in the input array.
Using only variables for max and min products saves memory and keeps the solution simple and fast.
7
ExpertSurprising Behavior with Multiple Negatives
🤔Before reading on: do you think more negative numbers always reduce the max product? Commit to yes or no.
Concept: Multiple negatives can increase the max product if they appear in pairs, flipping the sign twice.
For example, in [2, -3, -2, 4], the product of [-3, -2] is 6, which is positive and larger than either alone. The algorithm tracks this by updating max and min products carefully. This behavior can be tricky to predict without tracking both values.
Result
The algorithm correctly finds max product subarrays even with many negatives.
Understanding sign flips from pairs of negatives is crucial for mastering this problem.
Under the Hood
The algorithm maintains two running products at each step: the maximum and minimum product ending at the current index. This is because a negative number can turn the minimum product into a maximum one and vice versa. When a negative number is encountered, the algorithm swaps these two values before updating them. This way, it captures all possible sign changes and keeps track of the best product so far.
Why designed this way?
This approach was designed to handle the complexity introduced by negative numbers and zeros efficiently. Earlier methods tried checking all subarrays, which was slow. By tracking max and min products dynamically, the algorithm avoids redundant calculations and handles sign changes elegantly. Alternatives like brute force were rejected due to poor performance.
Start
  ↓
[Current Number]
  ↓
Check if negative?
  ├─ Yes → Swap maxProd and minProd
  └─ No  → Continue
  ↓
Update maxProd = max(current number, maxProd * current number)
Update minProd = min(current number, minProd * current number)
  ↓
Update global max result if maxProd is greater
  ↓
Move to next number
  ↓
Repeat until end
  ↓
Return global max result
Myth Busters - 4 Common Misconceptions
Quick: Do you think the maximum product subarray always includes the largest number in the array? Commit to yes or no.
Common Belief:The maximum product subarray must include the largest single number in the array.
Tap to reveal reality
Reality:The maximum product subarray can be a product of multiple numbers that together exceed any single number, especially when negatives multiply to a positive.
Why it matters:Assuming the largest number alone is the answer can cause missing the true maximum product, leading to incorrect solutions.
Quick: Do you think tracking only the maximum product so far is enough? Commit to yes or no.
Common Belief:Tracking only the maximum product at each step is enough to find the answer.
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 one.
Why it matters:Ignoring the minimum product causes failure on arrays with negative numbers, producing wrong results.
Quick: Do you think zeros always break the maximum product subarray? Commit to yes or no.
Common Belief:Zeros always prevent finding a maximum product subarray beyond zero.
Tap to reveal reality
Reality:Zeros reset the product calculation but the maximum product subarray can be before or after zeros, so zeros split the array into parts to consider separately.
Why it matters:Misunderstanding zeros leads to incorrect handling and missed maximum products in subarrays after zeros.
Quick: Do you think more negative numbers always reduce the maximum product? Commit to yes or no.
Common Belief:More negative numbers always reduce the maximum product because they flip signs.
Tap to reveal reality
Reality:An even number of negatives can produce a positive product larger than any single element.
Why it matters:Failing to consider pairs of negatives causes missing larger products formed by multiple negatives.
Expert Zone
1
Swapping max and min products only when the current number is negative is a subtle but critical step that ensures correct sign handling.
2
The algorithm can be adapted to return the actual subarray by tracking start and end indices alongside max and min products.
3
In some cases, resetting max and min products to 0 when encountering zeros can simplify implementation but requires careful handling to avoid missing single-element subarrays.
When NOT to use
This approach is not suitable if the problem requires non-contiguous elements or if the array is extremely large and memory is constrained; in such cases, segment trees or other data structures might be better. Also, if only sums are needed, simpler algorithms like Kadane's apply.
Production Patterns
In real-world systems, this pattern is used in financial modeling to find periods of maximum growth or loss, in signal processing to detect strongest signals, and in competitive programming as a classic dynamic programming example. Professionals often extend it to multidimensional arrays or streaming data.
Connections
Kadane's Algorithm
Builds-on
Maximum Product Subarray extends Kadane's Algorithm for sums by handling products and sign changes, deepening understanding of dynamic programming on arrays.
Sign Flipping in Mathematics
Same pattern
The way negative numbers flip product signs is a direct application of sign rules in multiplication, connecting algorithm behavior to basic math principles.
Stock Market Analysis
Application
Finding maximum product subarrays is similar to finding periods of maximum return in stock prices, showing how algorithms model real-world financial trends.
Common Pitfalls
#1Ignoring the minimum product and tracking only the maximum product.
Wrong approach: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: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 realizing that negative numbers can flip the sign, so minimum product can become maximum.
#2Not handling zeros properly, causing incorrect product calculations.
Wrong approach:maxProd = maxProd * nums[i]; minProd = minProd * nums[i]; // no reset when nums[i] == 0
Correct approach:if (nums[i] == 0) { maxProd = 0; minProd = 0; } else { // update maxProd and minProd normally }
Root cause:Failing to reset products when zero appears, which breaks continuous product calculation.
#3Trying to store max and min products for all indices unnecessarily.
Wrong approach:let maxProdArr = new Array(nums.length); let minProdArr = new Array(nums.length); // store products for all indices
Correct approach:Use variables to store only last maxProd and minProd values, updating them in place.
Root cause:Not recognizing that only the previous step's values are needed, leading to extra memory use.
Key Takeaways
Maximum Product Subarray requires tracking both maximum and minimum products at each step to handle negative numbers correctly.
Dynamic programming reduces the problem from checking all subarrays to a linear-time solution by updating running products.
Zeros reset the product calculation and split the array into segments to consider separately.
Swapping max and min products when encountering a negative number is the key insight to handle sign flips.
This problem connects to real-world applications like financial analysis and deepens understanding of array-based dynamic programming.

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 sum of its elements
B. The contiguous subarray with the largest product of its elements
C. The longest subarray with all positive numbers
D. The subarray with the smallest product of its elements

Solution

  1. Step 1: Understand the problem statement

    The problem asks for a contiguous part of the array where the product of all numbers is as large as possible.
  2. Step 2: Differentiate from similar problems

    This is different from finding the largest sum or smallest product; it specifically focuses on the product of elements in a continuous segment.
  3. Final Answer:

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

    Maximum product subarray means largest product segment [OK]
Hint: Look for continuous elements with max product, not sum [OK]
Common Mistakes:
  • Confusing product with sum
  • Ignoring that subarray must be contiguous
  • Thinking about longest subarray instead of max product
2. Which of the following TypeScript function signatures correctly represents a function to find the maximum product subarray?
easy
A. function maxProduct(nums: number[]): number
B. function maxProduct(nums: string): number
C. function maxProduct(nums: number): number[]
D. function maxProduct(nums: number[]): string

Solution

  1. Step 1: Check input parameter type

    The input should be an array of numbers, so nums: number[] is correct.
  2. Step 2: Check return type

    The function returns the maximum product value, which is a number, not an array or string.
  3. Final Answer:

    function maxProduct(nums: number[]): number -> Option A
  4. Quick Check:

    Input array, output number matches signature [OK]
Hint: Input is number array, output is single number [OK]
Common Mistakes:
  • Using string type for input or output
  • Returning array instead of number
  • Incorrect parameter types
3. What is the output of the following TypeScript code?
function maxProduct(nums: number[]): number {
  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;
}

console.log(maxProduct([2, 3, -2, 4]));
medium
A. 6
B. 4
C. -2
D. 24

Solution

  1. Step 1: Initialize variables and start loop

    maxProd, minProd, and result start at 2. Loop from index 1 to 3.
  2. Step 2: Iterate and update maxProd, minProd, and result

    At i=1 (3): maxProd = max(3, 2*3)=6, minProd = min(3, 2*3)=3, result=6.
    At i=2 (-2): nums[i]<0, 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.
    At i=3 (4): maxProd = max(4, -2*4) = max(4, -8) = 4.
    minProd = min(4, -12*4) = min(4, -48) = -48.
    result = max(6, 4) = 6.
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Max product subarray is [2,3] = 6 [OK]
Hint: Track max and min products, swap on negative [OK]
Common Mistakes:
  • Not swapping max and min on negative number
  • Only tracking max product, ignoring min product
  • Confusing max product with sum
4. Identify the bug in this TypeScript function for maximum product subarray:
function maxProduct(nums: number[]): number {
  let maxProd = 1;
  let minProd = 1;
  let result = Number.MIN_VALUE;
  for (let num of nums) {
    if (num < 0) {
      let temp = maxProd;
      maxProd = minProd;
      minProd = temp;
    }
    maxProd = Math.max(num, maxProd * num);
    minProd = Math.min(num, minProd * num);
    result = Math.max(result, maxProd);
  }
  return result;
}
medium
A. Initializing maxProd and minProd to 0 instead of 1
B. Not swapping maxProd and minProd when num is positive
C. Using a for loop instead of forEach
D. Using Number.MIN_VALUE instead of Number.NEGATIVE_INFINITY for result

Solution

  1. Step 1: Understand Number.MIN_VALUE usage

    Number.MIN_VALUE is the smallest positive number close to zero, not the most negative number.
  2. Step 2: Correct initialization for result

    To track maximum product correctly, result should start at Number.NEGATIVE_INFINITY to handle negative products properly.
  3. Final Answer:

    Using Number.MIN_VALUE instead of Number.NEGATIVE_INFINITY for result -> Option D
  4. Quick Check:

    Use Number.NEGATIVE_INFINITY for max tracking [OK]
Hint: Use Number.NEGATIVE_INFINITY for max initial value [OK]
Common Mistakes:
  • Confusing Number.MIN_VALUE with negative infinity
  • Not swapping max and min on negative number
  • Wrong initial values for maxProd and minProd
5. Given the array [-1, -3, -10, 0, 60], what is the maximum product subarray and its product?
hard
A. Subarray: [-1, -3, -10], Product: -30
B. Subarray: [-3, -10, 0], Product: 0
C. Subarray: [60], Product: 60
D. Subarray: [-10, 0, 60], Product: 0

Solution

  1. Step 1: Analyze subarrays and their products

    Check products of contiguous subarrays:
    [-1] = -1
    [-1, -3] = 3
    [-1, -3, -10] = -30
    [-3] = -3
    [-3, -10] = 30
    [-10] = -10
    [0] = 0
    [60] = 60
  2. Step 2: Identify maximum product

    The largest product found is 60 from subarray [60].
  3. Final Answer:

    Subarray: [60], Product: 60 -> Option C
  4. Quick Check:

    Max product is 60 from single element [60] [OK]
Hint: Check single elements and negative pairs carefully [OK]
Common Mistakes:
  • Assuming negative product is maximum
  • Ignoring single element subarrays
  • Confusing zero product with max product
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