VFlash: Fast, Accurate Visual Planning via Flash Primitive Decoding
u_Unrolled
DSA for AI/ML · Module 12: Dynamic programming

Lesson 12.14 of 16 in this module Unrolled Pro

Best Time to Buy and Sell Stock with Cooldown

Maximise profit from buying and selling one share at a time, where after selling you must wait one day before buying again. From trying every buy/sell/wait decision for every day (3^n), to a state machine with three states (holding, just sold, resting) whose best profits are updated day by day (O(n) time, O(1) space). Then a transaction fee, at most k transactions, no restrictions at all (where greedy works), and the ML connection: finite-horizon value iteration in a Markov decision process is this same state-by-day table.

about 10 min 3 Python examples 2 quick checks

Problem. prices[i] is a stock's price on day i. You may complete as many transactions as you like (buy one share, then sell it), holding at most one share at a time, but after you sell, you can't buy on the next day (a one-day cooldown). Return the maximum profit.

text
prices = [1, 2, 3, 0, 2]   →   3      (buy 1, sell 2, cooldown, buy 0, sell 2)
prices = [1]               →   0

The decision on each day depends on what you're doing right now: holding a share, having just sold (so today is a cooldown), or free to buy. Those three states, plus the day, are the whole DP: a state machine whose best value per state is updated once per day.

ML context. "Best total reward over time, where the allowed actions depend on the current state" is a Markov decision process. Finite-horizon value iteration in reinforcement learning computes, for every day and state, the best achievable return: exactly this lesson's table (Change D). The same state-machine DP schedules actions with recovery periods: retraining jobs with a cool-down between deployments, or rate-limited API calls.


1. Step 1: Clarify

That's the preview. Modules 00–01 are free; this lesson is part of Unrolled Pro.
Staff AI & Pro Tier Lesson

Unlock "Best Time to Buy and Sell Stock with Cooldown"

The foundations are free forever. Unrolled Pro unlocks the complete lesson, production architectures, and 55 battle-tested ML system design case studies.

Everything included with Pro:
All 234+ Deep-Dive Lessons across transformer internals, inference, RAG & agents
55 Staff-Level ML & System Design Case Studies with mathematical capacity estimates
AI Engineer Sheet & Exercises with worked solutions, self-checks, and code
100 Landmark Research Papers guided walkthroughs & progress tracking
14-Day Money-Back Guarantee — 100% full refund if you aren't satisfied
View Plans & Unlock All Lessons

From ₹167/mo (~$2/mo) · Cancel anytime · Instant activation

100% Risk-Free: 14-day no-questions-asked money-back guarantee