Saturday, July 30, 2016

DP - Longest increasing subsequence

The problem

Given a sequence of numbers S1,S2...,Sn
We have to find a sub-sequence


such that


The solution

First we create a table by scanning the number from start to end. For each number we find number with largest sequence that is smaller than the current number. We set length of current items sequence length to be one more the found number. We also set the predecessor of the current item to be the found numbers index.
From the table we see that the maximum length is 7 at index 10. So we start at index 10 which will be last item of the sub-sequence. The value is 16. Then we find its predecessor from the predecessor list at index 10 - which is 9. So the next to last item will be item at index 9 which is 12. Which has predecessor at index 7 and so on.
The longest increasing sub-sequence is:
1, 3, 4, 5, 7, 12, 16

Here is the code in python:


[This is incomplete but I may not complete it]


  1. Hi vaia, would you also cover O(n log n) solution? Thanks.

  2. This comment has been removed by a blog administrator.

  3. Our mortgage payment calculator provides you with everything you need to evaluate different scenarios, to assist you decide what mortgage is right to suit your needs. mortgage payment calculator canada Condo owners pay fixed monthly fees that cover costs, such as building insurance and property maintenance, elevators, roofing, fitness facilities and much more. mortgage calculator