Dynamic Programming21 sections · 916 units
Open in Course

Why Binary Search Works

Understanding the tails array

The tails array maintains the smallest ending element for each LIS length. tails[k]tails[k] = smallest last element of any LIS of length k+1k+1. Key invariant: tailstails is always sorted. Why? A longer LIS must end with a larger element than a shorter one ending at an earlier position.

When we see a new element xx: if x>tails[last]x > tails[last], we can extend. Otherwise, find the first tails[k]xtails[k] \geq x and replace it. Replacing keeps tailstails optimal: we now have a smaller ending element for that length, enabling more extensions later.