Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 300 Longest Increasing Subsequence - Binary Search Optimization

The optimization idea

The O(n2)O(n^2) bottleneck: for each element, we scan all previous elements. Can we do better? observation: maintain an array tailstails where tails[k]tails[k] is the smallest ending element of all increasing subsequences of length k+1k+1. When you see a new element xx:

1.1. If xx is larger than all elements in tailstails, append it (extends the longest subsequence).

2.2. Otherwise, find the smallest element in tailstails that is x\ge x and replace it with xx. Why replace? A smaller ending value gives more room to extend later. The length of tailstails is your answer.