#152

Maximum Product Subarray

Medium Kadane with min & max

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Find the contiguous subarray with the largest product and return the product.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the contiguous piece with the biggest product.

Why this works: a negative number flips the smallest product into the biggest, so track both the max and the min ending here.

Example: [2, 3, -2, 4]

max/min: 2/2, 6/3, -2/-12, 4/-48best = 6

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Updating max first and then using the new max to compute min — save the old values first.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Kadane, Dutch Flag & Moore's Voting
🎬 Episodes 11–13: video coming soon