-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongestNonDecreasing.py
57 lines (48 loc) · 1.67 KB
/
longestNonDecreasing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import random
def OneLongestNonDecreasing(prog):
"""
Return longest non-decreasing subsequence
:param prog: progression to find a subsequence
:return: length and end index of a subsequence
"""
length, v, end = 0, 1, 0
for i in range(1, len(prog)):
if prog[i] >= prog[i - 1]:
v += 1
else:
if v > length:
length, end = v, i
v = 1
return length, end
def LongestNonDecreasingWithHighestSum(prog):
"""
Return longest non-decreasing subsequence with the highest sum
:param prog: progression to find a subsequence with the highest sum
:return: length and end index of a subsequence with the highest sum
"""
length, v = 0, 1
progressions = []
for i in range(1, len(prog)):
if prog[i] >= prog[i - 1]:
v += 1
else:
if v >= length:
length = v
progressions.append(prog[i - v:i])
v = 1
max_sum = 0
max_arr = []
for p in [p for p in progressions if len(p) == length]:
if sum(p) > max_sum:
max_arr = p
max_sum = sum(p)
return max_sum, max_arr
progression = [random.randint(0, 100) for i in range(100)]
sub_length, index = OneLongestNonDecreasing(progression)
max_aggr, max_list = LongestNonDecreasingWithHighestSum(progression)
print("Generated array:")
print(', '.join([str(k) for k in progression]))
print("First longest non decreasing sub progression:")
print(f"{sub_length}:{[str(k) for k in progression[index - sub_length:index]]}")
print("Longest non decreasing sub progression with the biggest sum:")
print(f"{max_aggr}:{max_list}")