Learn / Dynamic programming

Stock buy and sell

Stock problems track a small state each day: holding a share or not, and how many transactions are left. Each day you either keep your state or buy (pay the price) or sell (receive it). With unlimited transactions the answer is all the rises; with k transactions keep buy[t] and sell[t] for each t.

How to recognise it

  • Prices over days, and buy and sell decisions.
  • A limit on the number of transactions, a fee, or a cooldown.
  • Holding at most one share at a time.

Holding or not

hold = -infinity; free = 0
each day p:
    hold = max(hold, free - p)      # keep holding, or buy today
    free = max(free, hold + p)      # keep waiting, or sell today
ProblemState
one transactionlowest price so far
unlimitedsum of every rise (or hold / free)
with a feehold / free, subtract the fee on selling
at most 2buy1, sell1, buy2, sell2
at most kbuy[t], sell[t] for t = 1..k

Common mistakes

  • Selling before buying on the same day in the formulas (update in the right order).
  • Starting hold at 0 instead of minus infinity.

Problems

0 of 5 solved

Check yourself

One transaction: what do you track?

Unlimited transactions: profit for [1, 2, 3, 4, 5]?

With a fee, when is it paid in the DP?

For at most k transactions, what does sell[t] depend on?