Learn / Dynamic programming

LIS family

The longest increasing subsequence has the state 'ends at index i': its length is 1 plus the best length ending at an earlier, smaller value. That O(n²) DP adapts to sums, divisibility, string chains, bitonic shapes and counting; patience sorting with binary search finds the length alone in O(n log n).

How to recognise it

  • The longest or best subsequence where neighbours must satisfy a rule.
  • Chains: pairs, words, divisible numbers.
  • Increasing then decreasing, or alternating up and down.

Ending at i

len[i] = 1 + max(len[j] for j < i with a[j] < a[i]), or 1
answer = max(len)
VariantChange
print italso store prev[i]; follow it back
maximum sumstore sums instead of lengths
number of LISalso store how many runs reach len[i]
divisible subsetsort; "a[j] divides a[i]" instead of <
string chainsort by length; predecessor = one letter removed
bitonicLIS from the left plus LIS from the right
alternatingtwo values: last move up, last move down

Faster length

Keep tails; for each value, binary search the first tail at least it and replace it (or append). The length of tails is the LIS length.

Common mistakes

  • Using <= when the problem needs strictly increasing.
  • Forgetting that tails is not itself an LIS.

Problems

0 of 11 solved

Check yourself

LIS of [10, 9, 2, 5, 3, 7, 101, 18]?

In the O(n log n) method, what does tails[k] hold?

For the longest bitonic subsequence, what is combined at each index?

Why sort pairs by end for the longest pair chain?