# Algorithm to determine longest increasing subsequence of a permutation

Let $\sigma$ be a permutation on {$1,...,n$}. We want to find the largest $m$ such that there exists an increasing subsequence $j_1, j_2, ..., j_m$ for which $\sigma(j_1), \sigma(j_2), ..., \sigma(j_m)$ is also increasing. Describe an algorithm which will determine $m$ using $O(n^2)$ time and $O(n)$ memory.

Solution Attempt:

Step 1: Store the list $\sigma(1),\sigma(2),...,\sigma(n)$ for reference.

Step 2: Check if $\sigma$ is the identity. If yes, we are done as $m = n$. Otherwise continue to step 3.

Step 3: Delete exactly one value from the list and check if the resulting sequence is increasing. Do this for each value. If we find one at any point we are done. Otherwise continue to Step 4.

Step 4: Delete exactly two values from the list and check if the resulting sequence is increasing... etc.

And so on, until we find $m$. I'm not sure how to check if this algorithm satisfies the conditions, though.

You can do this with dynamic programming.

Save an array $A$ of length $n+1$ such that $A[i]$ is the smallest possible value for an increasing subsequence of length $i$.

Initialize it to $A(0)=-\infty$, $A(1)=\sigma(1)$ and $A(j)=\infty$ for $j>1$.

After this we actualize the list $n-1$ to incorporate the other elements of the permutation.

So in step $j$ we do as follows.

From $k=n$ to $k=1$ we actualize $A(k)$ as follows: If $\sigma(j)<A(k)$ and $\sigma(j)>A(k-1)$ change $A(k)$ to $\sigma(j)$.

After doing this your answer is just the index of the last value in the list that isn't $\infty$.

• This is the algorithm based on "patience sorting." It can be easily implemented to run in $O(n \log n)$ time and $O(n)$ space. Within the same bounds one can also return the subsequence. – Fabio Somenzi Jan 2 '17 at 0:59

This does not satisfy the conditions.

For $k \ge 0$, step $(k+2)$ does $\binom{n}{k}$ checks. Each check requires $(n-k-1)$ comparisons.

There are at most $n+1$ steps in your algorithm, thus your algorithm runs $2^n$ checks at most, which means it does not run in $O(n^2)$ time (I have not done the exact calculations for its complexity though), even though it does use $O(n)$ memory.

Here's a hint for an $O(n^2)$ time algorithm: How can one relate the length of the longest increasing subsequence in the first $k$ elements to the length of the longest increasing subsequence in the first $1,2,\cdots,k-1$ elements?