The problem and the state
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.
Trying every subsequence means 2ⁿ choices: 256 for n = 8. Instead keep one number per position. L[i] is the length of the longest rising run that ends exactly at a[i]. Fixing the end helps: the next number only has to beat a[i].
Any single number is a rising run of length 1, so every cell starts at 1. Line 2 builds that table: L = [1] * len(a). The real work is deciding which cells can grow.
Filling the table
Fill L left to right. 3 and 1 have nothing smaller before them, so they keep 1. For a[2] = 4, look back: 3 < 4 and 1 < 4, so 4 extends either run. Both have length 1, so L[2] = 2.
a[3] = 1. Nothing before it is smaller: 1 < 1 is false, as a rising run must strictly increase. So L[3] stays 1. Full rule: L[i] = 1 + the largest L[j] with j < i and a[j] < a[i], or 1 if none.
The same rule fills the rest. 5 extends 4, so L[4] = 3. 9 extends 5: 4. 2 extends a 1: 2. 6 extends 5: 4. Each cell reads only cells to its left, and those are already final.
Answer, path and cost
The longest run can end anywhere, so the answer is the largest value in the table, not simply the last one: max(L) = 4. Two cells reach it: L[5] (runs ending at 9) and L[7] (runs ending at 6).
To get the run, walk back from a cell with L = 4. Each time, find an earlier smaller number whose L is one less. From 6: 5 (L = 3), then 4 (L = 2), then 1. The run is 1 4 5 6.
For each i, line 4 loops over every earlier j, so line 5 runs 0 + 1 + … + 7 = 28 times for n = 8. In general that is n(n − 1)/2 checks: Θ(n²) time. The table L adds Θ(n) memory.
Faster: keep tails[k], the smallest end of any rising run of length k + 1. Each number replaces the first tail not smaller than it (binary search), or is added at the end. The answer is the count of tails: 4, in Θ(n log n).
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.