|
1 | | -def longest_seq(seq): |
2 | | - """ returns the longest increasing subseqence |
3 | | - in a sequence """ |
| 1 | +""" |
| 2 | +Problem: http://www.geeksforgeeks.org/dynamic-programming-set-3-longest-increasing-subsequence/ |
| 3 | +""" |
| 4 | +def longest_increasing_subsequence(nums): |
| 5 | + # array used to store the length of the longest subsequence found |
4 | 6 | cache = [1] * len(nums) |
5 | | - solution = [0] * len(nums) |
| 7 | + |
| 8 | + # array used to store the location of the predecessor in the longest |
| 9 | + # subsequence. -1 by default |
| 10 | + location = [-1] * len(nums) |
6 | 11 |
|
7 | 12 | for i in range(1, len(nums)): |
8 | 13 | for j in range(0, i): |
9 | 14 | if nums[i] > nums[j]: |
10 | 15 | if cache[j] + 1 > cache[i]: |
11 | 16 | cache[i] = cache[j] + 1 |
12 | | - solution[i] = j |
13 | | - return max(cache), solution |
| 17 | + location[i] = j |
| 18 | + |
| 19 | + # finding the max in the cache gives us the |
| 20 | + # answer - i.e. length of the LIS |
| 21 | + max_value = max(cache) |
| 22 | + |
| 23 | + # with the answer in hand, we need to build the solution |
| 24 | + # using the locations stored |
| 25 | + solution = [] |
| 26 | + i = cache.index(max_value) |
| 27 | + |
| 28 | + # we start with the max value i.e. the index of the |
| 29 | + # location where the max LIS exists and then |
| 30 | + # keep backtracking to build up the solution |
| 31 | + while location[i] > -1: |
| 32 | + solution.append(nums[i]) |
| 33 | + i = location[i] |
| 34 | + |
| 35 | + # when the loop ends, just append the starting element |
| 36 | + solution.append(nums[i]) |
| 37 | + |
| 38 | + # return the length of the LIS and the solution (in reverse) |
| 39 | + return max_value, solution[::-1] |
14 | 40 |
|
15 | 41 | if __name__ == "__main__": |
16 | | - seq = [5, 2, 8, 10, 3, 6, 9, 7] |
17 | | - seq2 = [0, 8, 3, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] |
18 | | - seq3 = [10, 22, 9, 33, 21, 50, 41, 60, 80] |
19 | | - print longest_seq(seq3) |
| 42 | + assert longest_increasing_subsequence([3, 4, -1, 0, 6, 2, 3]) == (4, [-1, 0, 2, 3]) |
| 43 | + assert longest_increasing_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) == (6, [10, 22, 33, 50, 60, 80]) |
| 44 | + assert longest_increasing_subsequence([5,0,1,2,3,4,5,6,7,8,9,10,11,12, 2, 8, 10, 3, 6, 9, 7]) == (13, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) |
20 | 45 |
|
0 commit comments