Skip to content

Commit 630b74f

Browse files
authored
Merge pull request #230 from dsrao711/issue_227
Python solution for max sum in DSA450
2 parents df73b98 + 017b7a3 commit 630b74f

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

DSA 450 GFG/max_sum_bottom_up.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#https://practice.geeksforgeeks.org/problems/maximum-sum-problem2211/1/
2+
3+
4+
#Approach 2 - Bottom Up approach
5+
6+
7+
def maxSum(self, n):
8+
# code here
9+
dp = [0]*(n+1)
10+
dp[0] = 0
11+
if(n >= 1):
12+
dp[1] = 1
13+
for i in range(2 , n+1):
14+
dp[i] = max((dp[int(i/2)] + dp[int(i/3)] + dp[int(i/4)]) , i)
15+
16+
return dp[n]
17+
18+
19+
#{
20+
# Driver Code Starts
21+
#Initial Template for Python 3
22+
23+
if __name__ == '__main__':
24+
t = int(input())
25+
for _ in range(t):
26+
n = int(input())
27+
ob = Solution()
28+
print(ob.maxSum(n))
29+
# } Driver Code Ends

DSA 450 GFG/max_sum_memoization.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
#https://practice.geeksforgeeks.org/problems/maximum-sum-problem2211/1/
3+
4+
# Approach 1 - Memoization
5+
6+
from functools import lru_cache
7+
8+
class Solution:
9+
@lru_cache(maxsize = 1000)
10+
def maxSum(self, n):
11+
# code here
12+
if(n == 0 or n == 1):
13+
return n
14+
else:
15+
return max( (self.maxSum(n//2) + self.maxSum(n//3) + self.maxSum(n//4)) , n )
16+
17+
18+
19+
#{
20+
# Driver Code Starts
21+
#Initial Template for Python 3
22+
23+
if __name__ == '__main__':
24+
t = int(input())
25+
for _ in range(t):
26+
n = int(input())
27+
ob = Solution()
28+
print(ob.maxSum(n))
29+
# } Driver Code Ends
30+
31+

0 commit comments

Comments
 (0)