๐ Stock Trading DP: Become a Time-Traveling Trader!
Imagine you have a magical crystal ball that shows you stock prices for the next few days. You can see exactly how much a stock will cost on Monday, Tuesday, Wednesday, and so on.
Now hereโs the fun part: When should you buy? When should you sell? And sometimes, you might need to take a break before trading again!
This is the adventure of Stock Trading Dynamic Programming โ where we become the smartest traders in the universe!
๐ฏ Our Trading Adventures
Weโll master two exciting challenges:
- Best Time to Buy and Sell Stock I โ One simple trade to make the most money
- Best Time to Buy and Sell with Cooldown โ Multiple trades, but with a rest period
Letโs begin our journey!
๐ฅ Part 1: Best Time to Buy and Sell Stock I
The Story
Meet little Timmy. He has a lemonade stand, but he wants to try something new โ buying and selling toy stocks!
His dad shows him the toy stock prices for the week:
| Day | Monday | Tuesday | Wednesday | Thursday | Friday |
|---|---|---|---|---|---|
| Price | $7 | $1 | $5 | $3 | $6 |
Timmy can buy once and sell once. He wants to make the biggest profit possible!
Timmyโs Thinking
- Buy on Monday ($7), sell on Friday ($6)? Loss of $1 ๐ข
- Buy on Tuesday ($1), sell on Wednesday ($5)? Profit of $4 ๐
- Buy on Tuesday ($1), sell on Friday ($6)? Profit of $5 ๐
The best answer: Buy at $1, Sell at $6 = $5 profit!
๐ง The Simple Rule
Buy LOW, Sell HIGH โ but sell AFTER you buy!
We need to find:
- The smallest price to buy
- The biggest price after that day to sell
๐ How the Magic Works
Think of it like this:
- Walk through each day
- Keep track of the lowest price so far
- At each day, check: โIf I sell today, how much do I make?โ
- Remember the best profit youโve seen
graph TD A["Start with Day 1"] --> B["Track Minimum Price"] B --> C["Calculate Profit if Sold Today"] C --> D{Is this the best profit?} D -->|Yes| E["Update Best Profit"] D -->|No| F["Keep Current Best"] E --> G["Move to Next Day"] F --> G G --> H{More Days?} H -->|Yes| B H -->|No| I["Return Best Profit"]
๐ป The Code
def maxProfit(prices):
if not prices:
return 0
min_price = prices[0]
max_profit = 0
for price in prices:
# Update minimum if found lower
min_price = min(min_price, price)
# Check profit if we sell today
profit = price - min_price
# Update best profit
max_profit = max(max_profit, profit)
return max_profit
Letโs Trace Through!
Prices: [7, 1, 5, 3, 6]
| Day | Price | Min So Far | Profit Today | Best Profit |
|---|---|---|---|---|
| 1 | 7 | 7 | 0 | 0 |
| 2 | 1 | 1 | 0 | 0 |
| 3 | 5 | 1 | 4 | 4 |
| 4 | 3 | 1 | 2 | 4 |
| 5 | 6 | 1 | 5 | 5 โ |
Answer: $5 profit! ๐
๐จ Visual Understanding
Imagine the prices as a mountain range:
7
โฒ
โ
โ 6
โ โฒ
โ 5 โ
โ โฒ โ
โ โ 3 โ
โ โ โฒ โ
โ 1 โ โ โ
โ โฒ โ โ โ
โโโโโดโโโดโโโดโโโดโโโดโโโ
Mon Tue Wed Thu Fri
We want to buy at the valley ($1) and sell at the highest peak after it ($6)!
โก Why This Works
- Time Complexity: O(n) โ we look at each price once
- Space Complexity: O(1) โ we only remember 2 numbers
Itโs super fast because weโre clever โ we donโt compare every pair of days. We just remember the best buy price and check each sell price!
๐ง Part 2: Best Time to Buy and Sell with Cooldown
The New Challenge
Now Timmy is a bit older and wants to be a pro trader! But thereโs a new rule:
After you sell, you must WAIT one day before buying again!
Itโs like the stock market is saying: โTake a break! Cool down! Rest your brain!โ
The Rules
- You can do many trades (buy-sell, buy-sell, โฆ)
- After selling, you must skip one day before buying again
- You canโt hold multiple stocks (sell before you buy again)
๐ญ The Three States
Imagine youโre a trader with three possible moods each day:
- HOLD ๐ฆ โ โI own a stock right nowโ
- SOLD ๐ฐ โ โI just sold today! Time to rest tomorrowโ
- REST ๐ด โ โIโm cooling down or waiting to buyโ
graph LR REST["REST ๐ด"] -->|Buy| HOLD["HOLD ๐ฆ"] HOLD -->|Sell| SOLD["SOLD ๐ฐ"] SOLD -->|Cooldown| REST HOLD -->|Keep| HOLD REST -->|Wait| REST
๐ฒ State Transitions Explained
Letโs think about what can happen each day:
From REST ๐ด
- Buy a stock โ Go to HOLD
- Do nothing โ Stay in REST
From HOLD ๐ฆ
- Sell the stock โ Go to SOLD (and make money!)
- Keep holding โ Stay in HOLD
From SOLD ๐ฐ
- Must cooldown โ Go to REST (no choice!)
๐งฎ The DP Magic Formula
For each day, we calculate the best money we can have in each state:
hold[i] = max(hold[i-1], rest[i-1] - price[i])
"keep holding" OR "was resting, now buy"
sold[i] = hold[i-1] + price[i]
"was holding, now sell"
rest[i] = max(rest[i-1], sold[i-1])
"keep resting" OR "finished cooldown"
๐ป The Code
def maxProfit(prices):
if len(prices) <= 1:
return 0
# Initialize states
hold = -prices[0] # Bought on day 0
sold = 0 # Can't sell on day 0
rest = 0 # Starting fresh
for price in prices[1:]:
prev_hold = hold
prev_sold = sold
prev_rest = rest
# Update each state
hold = max(prev_hold, prev_rest - price)
sold = prev_hold + price
rest = max(prev_rest, prev_sold)
# Best profit: either just sold or resting
return max(sold, rest)
๐ Example Walkthrough
Prices: [1, 2, 3, 0, 2]
| Day | Price | HOLD | SOLD | REST | Explanation |
|---|---|---|---|---|---|
| 0 | 1 | -1 | 0 | 0 | Buy: -1, Canโt sell, Fresh start |
| 1 | 2 | -1 | 1 | 0 | Keep or buy, Sell: -1+2=1, Rest |
| 2 | 3 | -1 | 2 | 1 | Keep, Sell: -1+3=2, Cooled down |
| 3 | 0 | 1 | -1 | 2 | Buy: 1-0=1, Sell: -1+0=-1, Rest |
| 4 | 2 | 1 | 3 | 2 | Keep, Sell: 1+2=3, Rest |
Answer: max(3, 2) = $3 profit! ๐
What Happened?
- Buy at $1 (Day 0)
- Sell at $2 (Day 1) โ Profit: $1
- Cooldown (Day 2) โ Rest
- Buy at $0 (Day 3)
- Sell at $2 (Day 4) โ Profit: $2
Total: $1 + $2 = $3!
๐ข The State Machine Journey
graph TD D0["Day 0: Buy at $1"] --> D1["Day 1: Sell at $2"] D1 --> D2["Day 2: COOLDOWN"] D2 --> D3["Day 3: Buy at $0"] D3 --> D4["Day 4: Sell at $2"] style D0 fill:#e8f5e9 style D1 fill:#fff3e0 style D2 fill:#e3f2fd style D3 fill:#e8f5e9 style D4 fill:#fff3e0
โก Complexity
- Time: O(n) โ one pass through prices
- Space: O(1) โ just 3 variables!
๐ Key Takeaways
Stock Trading I
| Concept | Remember |
|---|---|
| Goal | One buy, one sell, max profit |
| Strategy | Track minimum, check each sell |
| Time | O(n) |
| Space | O(1) |
Stock Trading with Cooldown
| Concept | Remember |
|---|---|
| Goal | Multiple trades with rest day |
| Strategy | 3 states: HOLD, SOLD, REST |
| Transition | SOLD must go to REST |
| Time | O(n) |
| Space | O(1) |
๐ The Big Picture
Dynamic Programming for stocks is like having a smart diary:
- Remember the past โ What was the best position yesterday?
- Make smart choices today โ Buy, sell, or wait?
- Build towards tomorrow โ Each decision affects future options
Youโre not just trading โ youโre time traveling through possibilities and picking the best path!
๐ You Did It!
Congratulations! You now understand:
- โ How to find the best single trade
- โ How to handle cooldown periods
- โ The magic of state-based DP
- โ Why these solutions are super efficient
Go forth and conquer those stock problems! Youโre a DP Trading Master now! ๐
