Longest Increasing Subsequence & the Block Reorderer
In short: the longest increasing subsequence (LIS) is the longest run of
elements that keeps the original order but may skip some. A quadratic table,
best[i] = the longest rising run ending at i, finds it in O(n²). A faster
version keeps one number per length — the smallest possible ending value,
the tails row — and finds the length alone in O(n log n) with binary search.
The tails row is not the subsequence itself; only its length is the answer.

Quarry keeps every stored document as a list of numbered blocks, and its index
expects those numbers in ascending order. After a restore from backup, the
index comes back scrambled: [4, 1, 6, 2, 7, 3, 8, 5]. Rewriting a block is
slow, so Quarry wants to leave as many blocks where they are as it can and move
the rest. The blocks that can stay are the ones that are already in order
relative to each other. The longest such group is the longest increasing
subsequence, and everything outside it has to move.
This section ends with Quarry's diff engine, which shows what changed between two revisions of a document. Every lesson fills a table, starting here with the smallest: a single row.
Subsequence, not subarray
A subarray is a contiguous slice. A subsequence keeps the original order
but may skip elements. In [4, 1, 6, 2, 7, 3, 8, 5], the blocks 1, 2, 3, 5
form a rising subsequence even though other blocks sit between them. They can
all stay put: move the other four blocks into the gaps and the index is sorted.
The brute-force plan is to try every subsequence and keep the longest rising
one. Each element is either in or out, so a list of n elements has 2ⁿ
subsequences. Count just the rising ones in a short list first:
from itertools import combinations
blocks = [4, 1, 6, 2]
rising = 0
for size in range(1, len(blocks) + 1):
for pick in combinations(blocks, size):
if all(a < b for a, b in zip(pick, pick[1:])):
rising += 1
print(rising)