Maximum Product Subarray
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Find the largest product of any non-empty continuous sub-list.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1What happens to a very negative running product when you multiply by a negative number?
- Hint 2Keep both the biggest and the smallest product ending at each position.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A gambler's bet keeps multiplying his money by the multiplier on each ticket. A big loss multiplier like -50 looks terrible, but another -2 coming next turns it into a huge win. So he keeps two pockets: the best total so far and the worst total so far, because the worst can become the best with one more negative.
- The obvious way
Compute the product of every sub-list: O(n²).
- The key insight
At each number the new biggest product is the best of: the number alone, biggest x number, smallest x number. The new smallest is the worst of the same three. A negative number swaps the roles of biggest and smallest, which taking the max and min of all three handles automatically. A zero resets both.
- The algorithm
- Biggest = smallest = answer = the first number.
- For each next number: candidates = (the number, biggest x number, smallest x number).
- New biggest = max of candidates; new smallest = min of candidates (use the OLD values).
- Answer = max(answer, biggest).
Watch it run
Examplenumbers = [2, 3, -2, 4]
Start with 2: biggest 2, smallest 2.
biggest 2, smallest 2, answer 2
Where people slip
- Compute both new values from the OLD biggest and smallest (the tuple/temporary variables do this); updating biggest first corrupts smallest.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def max_product(nums):
biggest = smallest = answer = nums[0]
for number in nums[1:]:
candidates = (number, biggest * number, smallest * number)
biggest, smallest = max(candidates), min(candidates)
answer = max(answer, biggest)
return answerNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.