04
Stock buy / sell (DP — Kadane / Subarray Sub-pattern)
Walk the days and keep the best profit for each state you can be in (holding / free / cooling down). Each day's values come from the previous day's.
Signals in the problem statement
- ›
"buy and sell stock"
- ›
"at most one / unlimited transactions"
- ›
"cooldown", "fee"
- ›
pick non-overlapping pieces and maximise the total
What makes it different
More than one running value, and the update must use yesterday's values (copy them first). LC 689 is the same "best so far from the left / right" idea applied to fixed-size windows.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Best Time to Buy and Sell StockWalkthroughEasyBasic Anchor·LeetCode #121
- 2Best Time to Buy and Sell Stock IIWalkthroughMediumBasic Reinforcement·LeetCode #122
- 3Best Time to Buy and Sell Stock with CooldownWalkthroughMediumSlight Variation·LeetCode #309
- 4Maximum Sum of 3 Non-Overlapping SubarraysWalkthroughHardInterview-Level·LeetCode #689
Template
stock-template.cpp
// Stock states: carry the best profit for each state at the end of each day.
// Shown with a cooldown (after selling you must rest one day).
int maxProfitStates(const vector<int>& prices) {
long long hold = LLONG_MIN / 2; // holding a share
long long sold = LLONG_MIN / 2; // sold today (tomorrow is cooldown)
long long rest = 0; // free, allowed to buy
for (int p : prices) {
long long h = hold, s = sold, r = rest; // yesterday's values
hold = max(h, r - p); // keep holding, or buy today
sold = h + p; // sell what we held
rest = max(r, s); // stay free, or yesterday's sale cools down
}
return (int)max(rest, sold);
}
// One transaction: keep minPrice so far, profit = max(profit, p - minPrice).
// Unlimited, no cooldown: hold = max(hold, free - p); free = max(free, hold + p).Remember this · DP — Kadane / Subarray
Trigger
Maximum (or minimum) sum/product of a contiguous subarray, stock buy/sell, circular arrays.
Think
Is the best subarray ending at i either "i alone" or "best ending at i−1, plus i"?
Key question
Should I extend or restart?