CMD Guide
HomeDSACompany Practice

medium Maximum Product Subarray

Problem Statement

Given an integer array, find the contiguous subarray (at least one number in it) that has the maximum product. Return this maximum product.

Examples

    • Input: [2,3,-2,4]
    • Expected Output: 6
    • Justification: The subarray [2,3] has the maximum product of 6.
    • Input: [-2,0,-1]
    • Expected Output: 0
    • Justification: The subarray [0] has the maximum product of 0.
    • Input: [-2,3,2,-4]
    • Expected Output: 48
    • Justification: The subarray [-2,3,2,-4] has the maximum product of 48.

Constraints:

Try it yourself

Try solving this question here:

🎯 STRICT STANDOUT — Maximum Product Subarray — problem

0. Pattern family

Family: Kadane dual max/min product

1. Why / judgment (K3)

Negatives flip max↔min. Track running max and min products ending here; zero resets. Not plain Kadane sum.

2. Worked complexity / derivation (K11)

O(n) time O(1) space. DP arrays O(n) optional.

3. Pattern + recognition + when-NOT (K12)

Name: MAX PRODUCT WITH MIN-DUAL

Recognition: contiguous max product; negatives and zeros present.

When-NOT: Max sum subarray. Max product subsequence (non-contiguous) different. Non-empty constraint.

4. Edge hand-run (K13)

[2,3,-2,4]→6. [-2,0,-1]→0. All negative single max element. [0,2]→2.

5. Interviewer follow-ups & drills

Q1. Why min?
Model answer: min * negative can become new max.

Q2. Zero?
Model answer: Reset candidates to 0 / restart at next.

Q3. Swap trick?
Model answer: When x<0 swap max/min then update.

✅ Solution Maximum Product Subarray

Problem Statement

Given an integer array, find the contiguous subarray (at least one number in it) that has the maximum product. Return this maximum product.

Examples

    • Input: [2,3,-2,4]
    • Expected Output: 6
    • Justification: The subarray [2,3] has the maximum product of 6.
    • Input: [-2,0,-1]
    • Expected Output: 0
    • Justification: The subarray [0] has the maximum product of 0.
    • Input: [-2,3,2,-4]
    • Expected Output: 48
    • Justification: The subarray [-2,3,2,-4] has the maximum product of 48.

Constraints:

  • 1 <= nums.length <= 2*104
  • -10 <= nums[i] <= 10
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Solution

  • Initialization:

    • Start by initializing two variables, maxCurrent and minCurrent, to the first element of the array. These variables will keep track of the current maximum and minimum product, respectively.
    • Also, initialize a variable maxProduct to the first element of the array. This will store the maximum product found so far.
  • Iterate through the array:

    • For each number in the array (starting from the second number), calculate the new maxCurrent by taking the maximum of the current number, the product of maxCurrent and the current number, and the product of minCurrent and the current number.
    • Similarly, calculate the new minCurrent by taking the minimum of the current number, the product of maxCurrent and the current number, and the product of minCurrent and the current number.
    • Update maxProduct by taking the maximum of maxProduct and maxCurrent.
  • Handle negative numbers:

    • Since a negative number can turn a large negative product into a large positive product, we need to keep track of both the maximum and minimum product at each step.
  • Return the result:

    • After iterating through the entire array, maxProduct will have the maximum product of any subarray.

Algorithm Walkthrough

Using the input [2,3,-2,4]:

  • Start with maxCurrent = 2, minCurrent = 2, and maxProduct = 2.
  • For the next number, 3:
    • New maxCurrent = max(3, 2 * 3) = 6
    • New minCurrent = min(3, 2 * 3) = 3
    • Update maxProduct = max(2, 6) = 6
  • For the next number, -2:
    • New maxCurrent = max(-2, 3*(-2)) = -2
    • New minCurrent = min(-2, 6*(-2)) = -12
    • maxProduct remains 6
  • For the last number, 4:
    • New maxCurrent = max(4, -2*4) = 4
    • New minCurrent = min(4, -12*4) = -48
    • maxProduct remains 6
  • The final answer is 6.

Code

java
    // Initialize the current maximum, minimum, and the result
    int maxCurrent = nums[0];
    int minCurrent = nums[0];
    int maxProduct = nums[0];

    // Iterate through the array starting from the second element
    for (int i = 1; i < nums.length; i++) {
      // Store the current max value to handle negative numbers
      int temp = maxCurrent;

      // Update maxCurrent for the current number
      maxCurrent = Math.max(
        nums[i],
        Math.max(maxCurrent * nums[i], minCurrent * nums[i])
      );

      // Update minCurrent for the current number
      minCurrent = Math.min(
        nums[i],
        Math.min(temp * nums[i], minCurrent * nums[i])
      );

      // Update the result
      maxProduct = Math.max(maxProduct, maxCurrent);
    }

    return maxProduct;
  }

  public static void main(String[] args) {
    Solution sol = new Solution();
    System.out.println(sol.maxProduct(new int[] { 2, 3, -2, 4 })); // 6
    System.out.println(sol.maxProduct(new int[] { -2, 0, -1 })); // 0
    System.out.println(sol.maxProduct(new int[] { -2, 3, 2, -4 })); // 48
  }
}

Complexity Analysis

  • Time Complexity: O(n) - We iterate through the array only once.
  • Space Complexity: O(1) - We use a constant amount of space regardless of the input size.

🎯 STRICT STANDOUT — Solution Maximum Product Subarray

0. Pattern family

Family: Running max/min product

1. Why / judgment (K3)

Update imax, imin each step; ans tracks global max. Clear zero/negative cases in prose.

2. Worked complexity / derivation (K11)

Θ(n)/Θ(1).

3. Pattern + recognition + when-NOT (K12)

Name: DUAL KADANE PRODUCT

Recognition: contiguous product max.

When-NOT: Max sum; empty subarray (usually non-empty required).

4. Edge hand-run (K13)

[-2,3,-4]→24. Hand: after 3 max=3 min=-6; *−4 → max=24.

5. Interviewer follow-ups & drills

Q1. Init ans?
Model answer: ans=nums[0] not 0 (all-negative arrays).

Q2. Multiply order?
Model answer: Compute candidates from old max/min before overwrite.

Q3. Single element?
Model answer: Answer is that element.

🧩 Pattern · Dynamic Programming

Recognize it: Overlapping subproblems + optimal substructure; “count ways” or “min/max over choices” → memoise or fill a table.

▶ Visualize this problem (step it, predict each fork)
⛶ Open this problem debugger in explore mode
🤖 Don't fully get this? Learn it with Claude

Stuck on Maximum Product Subarray? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Maximum Product Subarray** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Maximum Product Subarray** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Maximum Product Subarray**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Maximum Product Subarray**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes