2.3 Longest increasing subsequence
Again we are given an array of integers. We want to compute the (or rather: a)
longest increasing subsequence. A subsequence
of a sequence
We write ISS for increasing subsequence and LISS for longest increasing subsequence. Here is an example:
So
Longest increasing subsequence differs from the previous two problems in that even the most trivial (and inefficient) algorithm is not completely trivial.
Exercise 2.3.1 Write test cases as described in Chapter 2.1
An exponential algorithm
Here is a simple recursive idea: let
- Compute
. - Compute the longest increasing subsequence
of whose maximum entry is less than ; then append . - Take the better of the two.
Note that in Point 2, we have to answer a more general question: what is the longest increasing subsequence with a specified upper bound.
Problem 2.3.2
Implement the above idea. Specifically, implement a recursive function
longest_increasing_subsequence_less_than(array, upper_bound).
You can then find the overall longest increasing subsequence
by calling it with upper_bound being
A quadratic algorithm
The previous idea was inefficient because a call to
longest_increasing_subsequence_less_than(array, inf) might entail
an exponential number of recursive calls. But how many different
input arguments (array, upper_bound) will the function encounter?
There are at most
To actually implement it, we turn things on their head, in a way. Rather than computing,
for each index
Note that if
How to compute the values
of
Since
What about
What about
In the example run below, we don't keep row for every
Once we have processed all elements, we have arrived at
Problem 2.3.3 Implement the idea that we just outlined. Start with a program that computes the length of the longest increasing subsequence, not the sequence itself.
Computing the sequence itself
We want our program to output a longest sequence, not just its length. To
facilitate judging the correctness, the answer should be unique, so we have
to come up with tie breaking rules: when two increasing subsequences
Theorem 2.3.1
Suppose
is also a LISS of
Remark: It is pretty easy to show that the new sequence
is increasing. In fact, this holds even if
Problem 2.3.4 Add bookkeeping to your implementation such that it does not only output the length of the LISS but the LISS with minimal values itself.
python quadratic.py < testcases/example-from-lecture-notes.in
6 4 6 7 8 11 12
Problem 2.3.5
Improve your implementation of the quadratic algorithm: in order to find
the