Skip to content

Instantly share code, notes, and snippets.

@st0le
Last active December 18, 2015 05:39
Show Gist options
  • Save st0le/5734546 to your computer and use it in GitHub Desktop.
Save st0le/5734546 to your computer and use it in GitHub Desktop.
Longest Increasing Subsequence DP
def longest_increasing_subsequence_dp(lst):
if not lst: return None
lis_len = []
prev = []
for i,v in enumerate(lst):
mx = 0
mxi = -1
for j in xrange(i):
if v > lst[j] and mx < lis_len[j]: #can v extend the current longest increasing subsequence?
mx = lis_len[j]
mxi = j
lis_len.append(1 + mx)
prev.append(mxi)
index = max(xrange(len(lst)),key=lis_len.__getitem__)
lis = []
while index >= 0: # go backwards till index < 0
lis.append(lst[index])
index = prev[index]
lis.reverse()
return lis
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment