a[0]3a[1]1a[2]4a[3]1a[4]5a[5]9a[6]2a[7]6L[0]L[1]L[2]L[3]L[4]L[5]L[6]L[7]1def lis(a):2 L = [1] * len(a)3 for i in range(len(a)):4 for j in range(i):5 if a[j] < a[i]:6 L[i] = max(L[i], L[j] + 1)7 return max(L)k=0k=1k=2k=3checks
Cells: the input a (back) and the DP table L (front), one per positionFrames: sand = the cell being filled (i), rose = the earlier cell compared (j)A hopping chip: L[j] + 1 carried to L[i]The input a at the back and the table L in front of it: L[i] is the length of the longest rising run that ends at a[i]. To fill L[i], a rose frame scans every earlier a[j]; when a[j] < a[i], a chip carries L[j] + 1 to L[i] and the cell keeps the larger value. The answer is max(L) = 4; walking back through cells one smaller gives the run 1 4 5 6. The tails row shows the faster Θ(n log n) method.

The problem and the state

  1. A subsequence keeps some numbers, in order, and may skip the rest. We want the longest one where each number is bigger than the one before. In 3 1 4 1 5 9 2 6, one answer is 3 4 5 9: length 4.

Filling the table

Answer, path and cost

What happens

;; step 1/10 · rising
a = [3, 1, 4, 1, 5, 9, 2, 6]
i        0   1   2   3   4   5   6   7
a        3   1   4   1   5   9   2   6

increasing subsequence: positions i₁ < i₂ < … with
a[i₁] < a[i₂] < …   (strictly bigger each time)
example: positions 0, 2, 4, 5 → 3 4 5 9
longest length: 4 (brute force over all 2^8 = 256 subsets agrees)

The state and transition follow MIT 6.006 (Spring 2020, Lecture 16), which uses the mirror image: the longest increasing subsequence of the suffix A[i:] that starts with A[i], filled right to left, in O(n²) time. CLRS chapter 14 covers the general method: optimal substructure, overlapping subproblems and rebuilding a solution from the table. This lesson asks for strictly increasing runs (a[j] < a[i]). For non-decreasing runs, where equal values may repeat, change the test to a[j] <= a[i] and use bisect_right in the fast method.