Magicsheet logo

Maximum Product Subarray

Medium
57.8%
Updated 6/1/2025

Maximum Product Subarray

1. What is this problem about?

The Maximum Product Subarray interview question is a classic dynamic programming challenge. Given an integer array, you need to find a contiguous non-empty subarray that has the largest product and return that product.

Unlike the "Maximum Sum Subarray" (Kadane's algorithm), products are trickier because multiplying two negative numbers results in a positive number. A very small (highly negative) product can suddenly become the maximum possible product if multiplied by another negative number.

2. Why is this asked in interviews?

This Maximum Product Subarray coding problem is one of the most frequently asked questions at companies like Apple, Google, and Amazon. It tests your ability to adapt a well-known algorithm (Kadane's) to a more complex scenario. It evaluates whether you can handle state transitions that depend on multiple values (current max and current min). Interviewers want to see if you can account for the "negative * negative = positive" edge case efficiently.

3. Algorithmic pattern used

The Array, Dynamic Programming interview pattern is the way to go. You maintain two variables at each position:

  1. max_so_far: The maximum product ending at the current position.
  2. min_so_far: The minimum product ending at the current position.

When you encounter a negative number, the max_so_far and min_so_far effectively swap their roles after multiplication. current_max = max(num, max_so_far * num, min_so_far * num) current_min = min(num, max_so_far * num, min_so_far * num)

4. Example explanation

Array: [2, 3, -2, 4, -1]

  • Start: res=2, max=2, min=2
  • Num 3: max = max(3, 2*3, 2*3) = 6, min = 3. res=6.
  • Num -2: max = max(-2, 6*-2, 3*-2) = -2, min = min(-2, -12, -6) = -12. res=6.
  • Num 4: max = max(4, -2*4, -12*4) = 4, min = -48. res=6.
  • Num -1: max = max(-1, 4*-1, -48*-1) = 48, min = -4. res=48.

Final Max Product is 48.

5. Common mistakes candidates make

The most common mistake in the Maximum Product Subarray coding problem is only keeping track of the current maximum. Candidates often forget that a large negative number can become a large positive number. Another mistake is not handling zeros correctly; a zero resets the product, and you might need to start a new subarray. Finally, forgetting to initialize the result with the first element of the array can lead to errors if the maximum product is negative.

6. Interview preparation tip

Always walk through your logic with an array that includes at least two negative numbers and one zero. This will help you verify if your min_so_far and max_so_far logic is robust. This problem is a perfect example of how "maintaining multiple states" can solve complex DP problems.

Similar Questions