Best Time to Buy and Sell Stock II - Problem

Imagine you're a day trader with perfect knowledge of future stock prices! You have an array prices where prices[i] represents the stock price on day i.

Your goal is to maximize profit by buying and selling strategically with these rules:

  • ๐Ÿ”น You can hold at most one share at any time
  • ๐Ÿ”น You can buy and sell multiple times
  • ๐Ÿ”น You can even buy and sell on the same day
  • ๐Ÿ”น You must buy before you sell

Return the maximum profit you can achieve.

Example: If prices = [7,1,5,3,6,4], you could:

  • Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 4
  • Buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 3
  • Total profit = 7

Input & Output

example_1.py โ€” Basic Case
$ Input: prices = [7,1,5,3,6,4]
โ€บ Output: 7
๐Ÿ’ก Note: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 3. Total profit = 7.
example_2.py โ€” Increasing Prices
$ Input: prices = [1,2,3,4,5]
โ€บ Output: 4
๐Ÿ’ก Note: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 4. Alternatively, you can buy and sell every day for the same total profit.
example_3.py โ€” Decreasing Prices
$ Input: prices = [7,6,4,3,1]
โ€บ Output: 0
๐Ÿ’ก Note: Since prices are always decreasing, no profit can be made. The best strategy is to never buy.

Visualization

Tap to expand
๐Ÿ† Optimal Stock Trading StrategyCapture Every Upward MovementPriceDays$7$1$5$3$6$4Buy $1 โ†’ Sell $5Profit: +$4Buy $3 โ†’ Sell $6Profit: +$3๐Ÿ’ฐ Total Profit: $4 + $3 = $7๐Ÿš€ Time: O(n) | Space: O(1)
Understanding the Visualization
1
Identify Price Increases
Scan through prices and find every day where price > previous day's price
2
Capture Each Profit
For each price increase, add the difference to our total profit
3
Sum All Gains
The sum of all positive price differences gives us maximum profit
Key Takeaway
๐ŸŽฏ Key Insight: Since we can perform unlimited transactions, the optimal strategy is to capture every single profitable price increase. This greedy approach guarantees maximum profit!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the price array

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a constant amount of extra space

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค prices.length โ‰ค 3 ร— 104
  • 0 โ‰ค prices[i] โ‰ค 104
  • You can perform multiple transactions
  • You can only hold at most one share at any time
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 25
89.5K Views
Very High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen