#122

Best Time to Buy and Sell Stock II

Medium Collect every rise

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

?The problem

You may buy and sell a stock many times (holding at most one share at a time). Return the maximum total profit.

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

◎Understanding

Really asking: many trades allowed; maximise profit.

Why this works: any profitable run equals the sum of its daily rises, so collect every rise.

Example: [7, 1, 5, 3, 6, 4]

rises: 1→5 (+4), 3→6 (+3)total 7

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Looking for the single best buy/sell pair — that's the one-transaction problem.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Greedy
🎬 Episodes 69–73: video coming soon