Overview
Stock problems involve a sequence of prices. At any day, you can choose to Buy, Sell, or Rest, subject to constraints (e.g. only hold 1 share at a time).
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Master the finite state machine approach to solve all variations of the "Best Time to Buy and Sell Stock" problems.
Stock problems involve a sequence of prices. At any day, you can choose to Buy, Sell, or Rest, subject to constraints (e.g. only hold 1 share at a time).
We represent the states as `dp[day][holding_status]`. `holding_status` is typically 0 (no stock) or 1 (holding 1 share).
From `0` to `1` costs `prices[i]`. From `1` to `0` adds `prices[i]`. Staying in the same state means doing nothing.
Because the state on day `i` only depends on day `i-1`, we can optimize the O(N) space down to O(1) using a few variables.