Stock Trading DP

Back

Loading concept...

๐Ÿ“ˆ 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:

  1. Best Time to Buy and Sell Stock I โ€” One simple trade to make the most money
  2. 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:

  1. Walk through each day
  2. Keep track of the lowest price so far
  3. At each day, check: โ€œIf I sell today, how much do I make?โ€
  4. 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

  1. You can do many trades (buy-sell, buy-sell, โ€ฆ)
  2. After selling, you must skip one day before buying again
  3. 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:

  1. HOLD ๐Ÿ“ฆ โ€” โ€œI own a stock right nowโ€
  2. SOLD ๐Ÿ’ฐ โ€” โ€œI just sold today! Time to rest tomorrowโ€
  3. 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?

  1. Buy at $1 (Day 0)
  2. Sell at $2 (Day 1) โ†’ Profit: $1
  3. Cooldown (Day 2) โ†’ Rest
  4. Buy at $0 (Day 3)
  5. 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:

  1. Remember the past โ€” What was the best position yesterday?
  2. Make smart choices today โ€” Buy, sell, or wait?
  3. 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! ๐Ÿ†

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.