Skip to content

Commit a607355

Browse files
committed
new code for LIS
1 parent 64f0abf commit a607355

File tree

2 files changed

+18
-24
lines changed

2 files changed

+18
-24
lines changed

dp/kadane.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
"""
2+
Problem: The maximum subarray problem is the task of finding the
3+
contiguous subarray within a one-dimensional array of numbers
4+
(containing at least one positive number) which has the largest sum.
5+
6+
Solution:
27
The recurrence relation that we solve at each step is the following -
38
49
Let S[i] = be the max value contigous subsequence till the ith element

dp/longest_subsequence.py

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,20 @@
11
def longest_seq(seq):
2-
""" returns the longest increasing subseqence
2+
""" returns the longest increasing subseqence
33
in a sequence """
4-
count = [1] * len(seq)
5-
prev = [0] * len(seq)
6-
for i in range(1, len(seq)):
7-
dist = []
8-
temp_prev = {}
9-
for j in range(i):
10-
if seq[j] < seq[i]:
11-
dist.append(count[j])
12-
temp_prev[count[j]] = j
13-
else:
14-
temp_prev[0] = j
15-
dist.append(0)
16-
count[i] = 1 + max(dist)
17-
prev[i] = temp_prev[max(dist)]
18-
19-
# path
20-
path = [seq[prev.index(max(prev))]]
21-
i = prev.index(max(prev))
22-
while i>1:
23-
path.append(seq[prev[i]])
24-
i = prev[i]
25-
return max(count), path[::-1]
4+
cache = [1] * len(nums)
5+
solution = [0] * len(nums)
6+
7+
for i in range(1, len(nums)):
8+
for j in range(0, i):
9+
if nums[i] > nums[j]:
10+
if cache[j] + 1 > cache[i]:
11+
cache[i] = cache[j] + 1
12+
solution[i] = j
13+
return max(cache), solution
2614

2715
if __name__ == "__main__":
2816
seq = [5, 2, 8, 10, 3, 6, 9, 7]
2917
seq2 = [0, 8, 3, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
30-
print longest_seq(seq2)
18+
seq3 = [10, 22, 9, 33, 21, 50, 41, 60, 80]
19+
print longest_seq(seq3)
3120

0 commit comments

Comments
 (0)