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)
| Variant | Change |
|---|---|
| print it | also store prev[i]; follow it back |
| maximum sum | store sums instead of lengths |
| number of LIS | also store how many runs reach len[i] |
| divisible subset | sort; "a[j] divides a[i]" instead of < |
| string chain | sort by length; predecessor = one letter removed |
| bitonic | LIS from the left plus LIS from the right |
| alternating | two 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
- Longest Increasing Subsequencemediumguide ready
- Print Longest Increasing Subsequencemediumguide ready
- Largest Divisible Subsetmediumguide ready
- Longest String Chainmediumguide ready
- Longest Bitonic Subsequencemediumguide ready
- Number of Longest Increasing Subsequencemediumguide ready
- Maximum Sum Increasing Subsequencemediumguide ready
- Longest subsequence such that difference between adjacent is onemediumguide ready
- Maximum Length of Pair Chainmediumguide ready
- Longest alternating subsequencemediumguide ready
- Weighted Job Schedulinghardguide ready