Skip to main content

Stock Trading with Cooldown

Also known as: Best Time to Buy and Sell Stock with Cooldown

Given prices[i] = stock price on day i Can buy and sell unlimited times, but must cooldown 1 day after selling Return maximum profit Example: [1,2,3,0,2] => 3 (buy@1, sell@2, cooldown, buy@0, sell@2)

Three states carry this: holding, sold today, free to buy. I move between them one day at a time and the cooldown enforces itself.

Examples

You write

max_profit(prices: List[int])

  1. Example 1

    Input
    prices = [1,2,3,0,2]
    returns
    3
  2. Example 2

    Input
    prices = [1]
    returns
    0

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Dynamic Programming

I reach for it when

  • Brute force repeats the same subproblem.
  • You are asked for a count, a minimum or a maximum.

Say this before you type. Say the state in one sentence, then say which smaller states it reads from.

All 37 Dynamic Programming problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Maximum Profit with Cooldownmedium