Lesson 33 of 40DP families
LIS, Subarray and State-Machine DP
Longest increasing subsequence in O(n log n), products and subarrays, stock problems as state machines, and prefix DP for decoding and word break.
A product analyst asks: what is the longest stretch of releases in which each one had a higher adoption rate than the last, even if a few releases in between broke the run? A trading backtest needs the best profit under rules like "one day's wait after every sale" or "a fee on every trade". A search box has to decide whether newyorkpizza splits into dictionary words. Each is a DP over a sequence, where the state is a position in the input plus, sometimes, a small amount of extra information about what has happened so far.
The Dynamic Programming lesson covered one-dimensional recurrences where dp[i] reads one or two earlier cells (stairs, house robber). Greedy covered Kadane. This lesson is the next level: states that read every earlier cell, a binary search that turns O(n²) into O(n log n), and the "state machine" trick that handles every stock-trading variant with the same three lines.
Longest increasing subsequence, the O(n²) way
Given nums, find the length of the longest strictly increasing subsequence. A subsequence keeps the original order but may skip elements: in [2, 6, 8, 3, 4, 5, 1] the answer is 4, from 2, 3, 4, 5.
The state that works is not "the best LIS in the first i elements", because that does not tell you what the last value was, and you need the last value to know whether you can extend it. Instead:
- State:
dp[i]= the length of the longest increasing subsequence that ends exactly at index i. - Recurrence: look at every earlier
jwithnums[j] < nums[i]; you can appendnums[i]to the best one:dp[i] = 1 + max(dp[j]), or 1 if there is none. - Answer:
max(dp), notdp[n-1]. The longest one can end anywhere.
"Ending exactly at i" is the key move in sequence DP. It pins down the last element so the recurrence knows what it can attach to. That is O(n²): fine for n up to a few thousand, too slow for 10⁵.
LIS in O(n log n): patience sorting
Keep an array tails, where tails[k] is the smallest possible last value of any increasing subsequence of length k + 1 seen so far. For each new x:
- If
xis bigger than every tail, it extends the longest subsequence: append it. - Otherwise find the first tail that is
>= xand replace it withx. A subsequence of that length can now end on a smaller value, which leaves more room to grow later.
tails is always sorted (a longer subsequence cannot end lower than the smallest ending of a shorter one), so finding the spot is a binary search with bisect_left. The length of tails at the end is the answer. n binary searches: O(n log n).
First value. The best length-1 subsequence ends at 2.
To recover a real subsequence, record for each element which index was the tail one position below it when it was placed (its parent). At the end, start from the index sitting in the last tail slot and follow parents back.
Press Run (⌘ Enter) to see what happens.The random test against brute force is not decoration. The O(n log n) version is easy to break with one wrong bisect or a parent recorded at the wrong moment, and 300 tiny random cases find those bugs faster than you can reason about them.
Using the tails method with bisect_left, what are the final tails and the LIS length for this input?
nums = [4, 10, 4, 3, 8, 9]
tails = []
for x in nums:
k = bisect_left(tails, x)
if k == len(tails):
tails.append(x)
else:
tails[k] = x
print(tails, len(tails))Strict or non-decreasing: one character
bisect_left finds the first tail >= x, so an equal value replaces a tail rather than extending past it: strictly increasing. For non-decreasing subsequences (equal values allowed), use bisect_right, which finds the first tail > x, so an equal value lands after its twin and can extend the run. Mixing these up gives an answer that is off by the number of duplicates, which a test with [2, 2, 2] catches instantly.
Russian Doll Envelopes
Envelopes (width, height) nest when both dimensions are strictly smaller. Find the longest chain. Sort by width, then run LIS on heights. The trap is equal widths: (6, 4) and (6, 7) cannot nest, but sorted by width then height ascending, the heights 4, 7 look like an increasing pair. Sort equal widths by height descending. Then within one width the heights decrease, so LIS can never pick two of them.
Press Run (⌘ Enter) to see what happens.The same "sort one dimension, LIS the other" idea solves box stacking and scheduling problems in two dimensions. LIS also hides in "minimum deletions to make the array sorted" (n minus LIS length).
Counting the longest ones
Number of Longest Increasing Subsequence asks how many LIS there are. Keep two arrays: length[i] as before, and count[i], the number of subsequences of that length ending at i. When an earlier j gives a strictly longer run, replace the count; when it ties, add to it. The answer sums count[i] over every i whose length equals the maximum. This is O(n²); the O(n log n) version needs a Fenwick tree or segment tree over values, which interviewers rarely expect.
Press Run (⌘ Enter) to see what happens.Subarrays: Kadane as DP, and products
Kadane's algorithm from the Greedy lesson is really a DP with the same "ending exactly here" state: best_ending_here = max(x, best_ending_before + x). Either extend the previous subarray or start fresh at x. Seeing it as DP is what lets you adapt it.
Maximum Product Subarray breaks plain Kadane. A large negative product is terrible now, but one more negative number turns it into the largest. So the state has to carry both extremes: the largest and the smallest product of a subarray ending here. At each x, the new extremes come from x alone, hi * x or lo * x. A zero resets both to 0, and starting fresh at the next x handles it.
Press Run (⌘ Enter) to see what happens.Compute both new values from the old hi and lo at the same time. Updating hi first and then using the new hi to compute lo is the classic bug here; the tuple assignment above avoids it.
What does max_product return for [-1, -2, -3, 0, 5]?
print(max_product([-1, -2, -3, 0, 5]))
Stock problems as a state machine
There is a whole family of "best time to buy and sell stock" problems. Learn them one by one and you memorise six solutions. Learn the pattern and you write each in a minute: on any day you are in one of a few states, each state keeps the best profit you can have while in it, and each price moves you between states.
For Best Time with Cooldown (after you sell, you must wait one day before buying):
hold: you own a share.sold: you sold today, so tomorrow is a forced rest.rest: you own nothing and are free to buy.
Transitions for price p:
hold = max(hold, rest - p): keep holding, or buy today, but only fromrest, never straight fromsold. That one restriction is the cooldown.sold = hold + p: sell what you hold.rest = max(rest, sold): stay out, or yesterday's sale finished its cooldown.
Start in rest with 0 profit. You may buy from here.
Day 0: buy at 1, so hold = -1. You cannot have sold anything yet (minus infinity), and rest = 0.
The other variants change only the states and edges:
- Transaction fee: two states,
holdandcash. Subtract the fee on the sell edge:cash = max(cash, hold + p - fee). - At most k transactions: one
buy[j]andsell[j]per transaction number j, wherebuy[j]can only come fromsell[j - 1]. O(n × k). If k is at least n / 2 you can never use them all, so just take every upward move. - Unlimited, no rules (Stock II): the fee version with fee 0, or simply the sum of all positive day-to-day changes.
Press Run (⌘ Enter) to see what happens.The same idea goes well beyond stocks. Any problem where "what am I allowed to do next" depends on a small amount of history (last action, whether something is open, how many times you have done X) becomes a set of states, one variable each, updated together per element. Paint House (no two neighbours the same colour) and "longest run with at most one deletion" fit the same mould.
Match each stock rule to how the state machine changes.
Prefix DP over strings
Two string problems use the plainest sequence state there is, dp[i] = the answer for the first i characters, and both are mostly about edge cases.
Decode Ways. Letters A to Z are encoded as 1 to 26. Count the ways to decode a digit string. The last letter either used one digit or two:
- one digit: allowed if that digit is not
"0"(there is no letter 0), addsdp[i-1]; - two digits: allowed if they form 10 to 26, adds
dp[i-2]."05"is not 5: a leading zero makes it invalid, and the range check catches it becauseint("05")is 5, below 10.
So "10" decodes one way (J), "100" decodes zero ways (the last 0 can neither stand alone nor pair as "00"), and a string starting with "0" is 0. Only the last two values are read, so two variables are enough.
Word Break. Can s be split into dictionary words? ok[i] is true if some j < i has ok[j] true and s[j:i] in the dictionary. Naively that is O(n²) slices, each costing up to O(n) to hash. The fix seniors reach for: only try j within the longest word length of i. With a dictionary of short words and a long string, that turns O(n²) into O(n × L).
Press Run (⌘ Enter) to see what happens.Notice what word_break does not do: it does not list the splits. Listing them (Word Break II) can produce exponentially many answers, so it needs backtracking, with this boolean table used to prune branches that cannot finish.
How to spot which sequence DP you need
- "Longest/shortest subsequence with an order condition":
dp[i]ending at i, O(n²); look for the tails trick if n is large and the condition is a comparison. - "Best contiguous subarray": Kadane-style "ending here" state; add a second variable if a sign flip or a deletion can change what is best.
- Rules that depend on what you did last: name the states, draw the edges, one variable per state.
- "Ways to split or decode a string": prefix DP,
dp[i]over the first i characters, with a bound on how far back to look.
- ending-at-i state
- dp[i] describes the best answer that ends exactly at index i, so the recurrence knows the last element. Answer is usually max over all i.
- patience sorting
- The O(n log n) LIS method: keep the smallest tail for each length and binary search where each new value goes.
- tails array
- tails[k] = smallest last value of an increasing subsequence of length k + 1. Sorted, gives the length, not the sequence.
- state machine DP
- A few named states (hold, sold, rest), each with its best value, updated together for every element by following allowed transitions.
- prefix DP
- dp[i] = the answer for the first i elements or characters, built from shorter prefixes.
- Kadane's recurrence
- best ending here = max(x, best ending before + x). Extend or restart.