-
Notifications
You must be signed in to change notification settings - Fork 827
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
64f0abf
commit a607355
Showing
2 changed files
with
18 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,20 @@ | ||
def longest_seq(seq): | ||
""" returns the longest increasing subseqence | ||
""" returns the longest increasing subseqence | ||
in a sequence """ | ||
count = [1] * len(seq) | ||
prev = [0] * len(seq) | ||
for i in range(1, len(seq)): | ||
dist = [] | ||
temp_prev = {} | ||
for j in range(i): | ||
if seq[j] < seq[i]: | ||
dist.append(count[j]) | ||
temp_prev[count[j]] = j | ||
else: | ||
temp_prev[0] = j | ||
dist.append(0) | ||
count[i] = 1 + max(dist) | ||
prev[i] = temp_prev[max(dist)] | ||
|
||
# path | ||
path = [seq[prev.index(max(prev))]] | ||
i = prev.index(max(prev)) | ||
while i>1: | ||
path.append(seq[prev[i]]) | ||
i = prev[i] | ||
return max(count), path[::-1] | ||
cache = [1] * len(nums) | ||
solution = [0] * len(nums) | ||
|
||
for i in range(1, len(nums)): | ||
for j in range(0, i): | ||
if nums[i] > nums[j]: | ||
if cache[j] + 1 > cache[i]: | ||
cache[i] = cache[j] + 1 | ||
solution[i] = j | ||
return max(cache), solution | ||
|
||
if __name__ == "__main__": | ||
seq = [5, 2, 8, 10, 3, 6, 9, 7] | ||
seq2 = [0, 8, 3, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] | ||
print longest_seq(seq2) | ||
seq3 = [10, 22, 9, 33, 21, 50, 41, 60, 80] | ||
print longest_seq(seq3) | ||
|