-
Notifications
You must be signed in to change notification settings - Fork 1k
/
maximum_sum_decreasing_subsequence.py
57 lines (43 loc) · 1.67 KB
/
maximum_sum_decreasing_subsequence.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
"""
Python program to implement Maximum Sum Decreasing Subsequence
In this problem, given an array we have to find the maximum sum an decreasing subsequence of that array can make.
This problem is a slight modification to the Longest Decreasing subsequence problem.
The problem can be solved using Dynamic Programming
"""
def maximum_sum_decreasing_subsequence(arr, n):
max_sum = 0
dp = [0 for i in range(n)]
# Initialize the dp array with the array values, as the maximum sum
# at each point is atleast as the value at that point
for i in range(n):
dp[i] = arr[i]
for i in range(1, n):
for j in range(i):
if(arr[i] < arr[j] and dp[i] < dp[j] + arr[i]):
dp[i] = dp[j] + arr[i]
# Now Find the maximum element in the dp array
max_sum = max(dp)
return max_sum
if __name__ == '__main__':
print("What is the length of the array? ", end="")
n = int(input())
if (n <= 0):
print("No numbers present in the array!!!")
exit()
print("Enter the numbers: ", end="")
arr = [int(x) for x in input().split(' ')]
res = maximum_sum_decreasing_subsequence(arr, n)
print("The maximum sum of an decreasing subsequence of the given array is {}".format(res))
"""
Time Complexity: O(num ^ 2), where 'num' is the size of the given array
Space Complexity: O(num)
SAMPLE INPUT AND OUTPUT
SAMPLE 1
What is the length of the array? 10
Enter the numbers: 23 14 5 84 24 222 321 43 123 432
The maximum sum of an decreasing subsequence of the given array is 444
SAMPLE 2
What is the length of the array? 5
Enter the numbers: 5 4 3 2 1
The maximum sum of an decreasing subsequence of the given array is 15
"""