For example, the longest increasing subsequence of “1, 100, 2, 101, 3” is “1, 2, 3,” which has a length of 3.
One way to solve this is by defining to be the maximum length of an increasing subsequence ending at, and including, the
th element. We can fill out
in order of increasing
and each update takes
time. Therefore, this solution takes a total of
time.
There is an solution, but it's harder to come up with. Once you know the answer you can prove it correct, though.
The idea is to iterate over in order and maintain an auxilliary array
At each step, if
is strictly greater than the last element of
then append
to the end of
Otherwise, use binary search to find the first element in
which is strictly greater than
and replace that element with
After processing all
the length of
is the length of the maximum increasing subsequence.
You can show the correctness of this algorithm with the following loop invariants:
The second loop invariant allows you to use binary search at each step. With a little thought you can convince yourself or your interviewer that these conditions are preserved at every step.