Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is some python code with tests which implements the algorithm running in O(n*log(n)). I found this on a the <a href="http://en.wikipedia.org/wiki/Talk%3aLongest_increasing_subsequence" rel="nofollow">wikipedia talk page</a> about the <a href="http://en.wikipedia.org/wiki/Longest_increasing_subsequence" rel="nofollow">longest increasing subsequence</a>. </p> <pre><code>import unittest def LongestIncreasingSubsequence(X): """ Find and return longest increasing subsequence of S. If multiple increasing subsequences exist, the one that ends with the smallest value is preferred, and if multiple occurrences of that value can end the sequence, then the earliest occurrence is preferred. """ n = len(X) X = [None] + X # Pad sequence so that it starts at X[1] M = [None]*(n+1) # Allocate arrays for M and P P = [None]*(n+1) L = 0 for i in range(1,n+1): if L == 0 or X[M[1]] &gt;= X[i]: # there is no j s.t. X[M[j]] &lt; X[i]] j = 0 else: # binary search for the largest j s.t. X[M[j]] &lt; X[i]] lo = 1 # largest value known to be &lt;= j hi = L+1 # smallest value known to be &gt; j while lo &lt; hi - 1: mid = (lo + hi)//2 if X[M[mid]] &lt; X[i]: lo = mid else: hi = mid j = lo P[i] = M[j] if j == L or X[i] &lt; X[M[j+1]]: M[j+1] = i L = max(L,j+1) # Backtrack to find the optimal sequence in reverse order output = [] pos = M[L] while L &gt; 0: output.append(X[pos]) pos = P[pos] L -= 1 output.reverse() return output # Try small lists and check that the correct subsequences are generated. class LISTest(unittest.TestCase): def testLIS(self): self.assertEqual(LongestIncreasingSubsequence([]),[]) self.assertEqual(LongestIncreasingSubsequence(range(10,0,-1)),[1]) self.assertEqual(LongestIncreasingSubsequence(range(10)),range(10)) self.assertEqual(LongestIncreasingSubsequence(\ [3,1,4,1,5,9,2,6,5,3,5,8,9,7,9]), [1,2,3,5,8,9]) unittest.main() </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload