Skip to content

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.

25 min read0/4 questions

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 j with nums[j] < nums[i]; you can append nums[i] to the best one: dp[i] = 1 + max(dp[j]), or 1 if there is none.
  • Answer: max(dp), not dp[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 x is bigger than every tail, it extends the longest subsequence: append it.
  • Otherwise find the first tail that is >= x and replace it with x. 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).

tails for nums = [2, 6, 8, 3, 4, 5, 1]
2
0
x = 2

First value. The best length-1 subsequence ends at 2.

1/6

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.

Python
from bisect import bisect_leftfrom itertools import combinationsimport random def lis_quadratic(nums): # dp[i] = length of the longest increasing subsequence ENDING at i dp = [1] * len(nums) for i in range(len(nums)): for j in range(i): if nums[j] < nums[i]: dp[i] = max(dp[i], dp[j] + 1) return max(dp, default=0) def lis(nums): # tails[k] = smallest possible tail of an increasing subsequence of length k + 1 tails, tail_idx = [], [] # values, and the index each came from parent = [-1] * len(nums) for i, x in enumerate(nums): k = bisect_left(tails, x) # first tail >= x (strictly increasing) if k == len(tails): tails.append(x) tail_idx.append(i) else: tails[k] = x tail_idx[k] = i parent[i] = tail_idx[k - 1] if k > 0 else -1 # rebuild by following parents back from the last tail seq, i = [], tail_idx[-1] if tail_idx else -1 while i != -1: seq.append(nums[i]) i = parent[i] return tails, seq[::-1] tails, seq = lis([2, 6, 8, 3, 4, 5, 1])print("tails:", tails, " real LIS:", seq)assert tails == [1, 3, 4, 5] and seq == [2, 3, 4, 5]assert lis([])[1] == [] and lis_quadratic([]) == 0 def brute(nums): for k in range(len(nums), 0, -1): for idx in combinations(range(len(nums)), k): vals = [nums[i] for i in idx] if all(a < b for a, b in zip(vals, vals[1:])): return k return 0 random.seed(7)for _ in range(300): nums = [random.randint(0, 9) for _ in range(random.randint(0, 9))] t, s = lis(nums) assert len(t) == len(s) == lis_quadratic(nums) == brute(nums) assert all(a < b for a, b in zip(s, s[1:]))
Output
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.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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.

Python
from bisect import bisect_left, bisect_right def lis_length(nums, strict=True): tails = [] find = bisect_left if strict else bisect_right for x in nums: k = find(tails, x) if k == len(tails): tails.append(x) else: tails[k] = x return len(tails) assert lis_length([2, 2, 2]) == 1 # strictly increasingassert lis_length([2, 2, 2], strict=False) == 3 # non-decreasingassert lis_length([1, 3, 3, 2, 3], strict=False) == 4 def max_envelopes(envelopes): # width ascending; for equal widths, height DESCENDING envelopes.sort(key=lambda e: (e[0], -e[1])) return lis_length([h for _, h in envelopes]) assert max_envelopes([[5, 4], [6, 4], [6, 7], [2, 3]]) == 3assert max_envelopes([[1, 1], [1, 2], [1, 3]]) == 1 # same width never nestsprint(lis_length([2, 2, 2]), lis_length([2, 2, 2], strict=False), max_envelopes([[5, 4], [6, 4], [6, 7], [2, 3]]))
Output
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).

Quick check
For Russian Doll Envelopes, why sort equal widths by height descending?
Need a nudge? A hint rules out a wrong answer.

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.

Python
def count_lis(nums): n = len(nums) length = [1] * n # longest increasing subsequence ending at i count = [1] * n # how many of those there are for i in range(n): for j in range(i): if nums[j] < nums[i]: if length[j] + 1 > length[i]: # strictly better: replace length[i] = length[j] + 1 count[i] = count[j] elif length[j] + 1 == length[i]: # another way to tie: add count[i] += count[j] best = max(length, default=0) return sum(c for l, c in zip(length, count) if l == best) assert count_lis([1, 3, 5, 4, 7]) == 2 # 1 3 5 7 and 1 3 4 7assert count_lis([2, 2, 2, 2, 2]) == 5 # each single 2assert count_lis([1, 2, 4, 3, 5, 4, 7, 2]) == 3assert count_lis([]) == 0print(count_lis([1, 3, 5, 4, 7]), count_lis([2, 2, 2, 2, 2]))
Output
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.

Python
def max_subarray(nums): # dp: best sum of a subarray ENDING here = max(x, best_ending_before + x) best = cur = nums[0] for x in nums[1:]: cur = max(x, cur + x) best = max(best, cur) return best def max_product(nums): # track both: a very negative product becomes the max after a negative number hi = lo = best = nums[0] for x in nums[1:]: candidates = (x, hi * x, lo * x) hi, lo = max(candidates), min(candidates) best = max(best, hi) return best assert max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6assert max_product([2, 3, -2, 4]) == 6assert max_product([-2, 3, -4]) == 24 # the two negatives cancelassert max_product([-2, 0, -1]) == 0 # zero resets the runassert max_product([-3]) == -3print(max_product([2, 3, -2, 4]), max_product([-2, 3, -4]))
Output
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.

Predict the outputPython

What does max_product return for [-1, -2, -3, 0, 5]?

print(max_product([-1, -2, -3, 0, 5]))
Need a nudge? Hints walk you through it.

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 from rest, never straight from sold. 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.
Cooldown as three states
restholdsoldbuy: -psell: +pwait

currentwaitingdone

Start in rest with 0 profit. You may buy from here.

1/4
Cooldown on prices [1, 2, 3, 0, 2]
p=1p=2p=3p=0p=2
hold-1
sold-inf
rest0

Day 0: buy at 1, so hold = -1. You cannot have sold anything yet (minus infinity), and rest = 0.

1/4

The other variants change only the states and edges:

  • Transaction fee: two states, hold and cash. Subtract the fee on the sell edge: cash = max(cash, hold + p - fee).
  • At most k transactions: one buy[j] and sell[j] per transaction number j, where buy[j] can only come from sell[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.
Python
NEG = float("-inf") def with_cooldown(prices): hold, sold, rest = NEG, NEG, 0 # before day 0: cannot hold or have sold for p in prices: hold, sold, rest = ( max(hold, rest - p), # keep holding, or buy (only from rest) hold + p, # sell today: tomorrow is a cooldown max(rest, sold), # stay out, or finish the cooldown ) return max(sold, rest) def with_fee(prices, fee): hold, cash = NEG, 0 for p in prices: hold, cash = max(hold, cash - p), max(cash, hold + p - fee) return cash def at_most_k(prices, k): if k >= len(prices) // 2: # enough trades to take every rise return sum(max(0, b - a) for a, b in zip(prices, prices[1:])) buy = [NEG] * (k + 1) # buy[j]: best cash while holding the j-th share sell = [0] * (k + 1) # sell[j]: best cash after the j-th sale for p in prices: for j in range(1, k + 1): buy[j] = max(buy[j], sell[j - 1] - p) sell[j] = max(sell[j], buy[j] + p) return sell[k] assert with_cooldown([1, 2, 3, 0, 2]) == 3 # buy 1, sell 2, rest, buy 0, sell 2assert with_cooldown([1]) == 0assert with_fee([1, 3, 2, 8, 4, 9], 2) == 8assert at_most_k([3, 3, 5, 0, 0, 3, 1, 4], 2) == 6assert at_most_k([2, 4, 1], 2) == 2assert at_most_k([3, 2, 6, 5, 0, 3], 2) == 7assert at_most_k([1, 2, 3, 4, 5], 1) == 4print(with_cooldown([1, 2, 3, 0, 2]), with_fee([1, 3, 2, 8, 4, 9], 2), at_most_k([3, 3, 5, 0, 0, 3, 1, 4], 2))
Output
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 the pairs0/4 matched

Match each stock rule to how the state machine changes.

Choose an item, then its match on the other side.

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), adds dp[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 because int("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).

Python
def num_decodings(s): # dp[i] = ways to decode the first i characters prev2, prev1 = 1, 1 if s and s[0] != "0" else 0 # dp[0], dp[1] for i in range(2, len(s) + 1): cur = 0 if s[i - 1] != "0": # last char as one letter (1-9) cur += prev1 if 10 <= int(s[i - 2:i]) <= 26: # last two chars as one letter (10-26) cur += prev2 prev2, prev1 = prev1, cur return prev1 if s else 0 assert num_decodings("12") == 2 # AB, Lassert num_decodings("226") == 3 # BBF, BZ, VFassert num_decodings("06") == 0 # leading zeroassert num_decodings("10") == 1 # only Jassert num_decodings("100") == 0 # "00" and a lone "0" are invalidassert num_decodings("2101") == 1 # 2 10 1assert num_decodings("") == 0 def word_break(s, words): words = set(words) longest = max(map(len, words), default=0) ok = [True] + [False] * len(s) # ok[i]: s[:i] can be split for i in range(1, len(s) + 1): for j in range(max(0, i - longest), i): # only words that could fit if ok[j] and s[j:i] in words: ok[i] = True break return ok[len(s)] assert word_break("leetcode", ["leet", "code"])assert word_break("applepenapple", ["apple", "pen"])assert not word_break("catsandog", ["cats", "dog", "sand", "and", "cat"])assert word_break("", ["a"])print(num_decodings("226"), num_decodings("2101"), word_break("leetcode", ["leet", "code"]))
Output
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.
Key terms
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.