2Brute2Best
🔥0
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”
  1. 1
    Best Time to Buy and Sell Stock
    Basic Anchor·LeetCode #121
    Easy
  2. 2
    Best Time to Buy and Sell Stock II
    Basic Reinforcement·LeetCode #122
    Medium
  3. 3
    Best Time to Buy and Sell Stock with Cooldown
    Slight Variation·LeetCode #309
    Medium
  4. 4
    Maximum Sum of 3 Non-Overlapping Subarrays
    Interview-Level·LeetCode #689
    Hard

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?