Skip to content

Commit 03cce7f

Browse files
committed
Python solution for max sum in DSA450
1 parent df73b98 commit 03cce7f

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

DSA 450 GFG/max_sum.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
32+
#Approach 2 - Bottom Up approach
33+
34+
35+
def maxSum(self, n):
36+
# code here
37+
dp = [0]*(n+1)
38+
dp[0] = 0
39+
if(n >= 1):
40+
dp[1] = 1
41+
for i in range(2 , n+1):
42+
dp[i] = max((dp[int(i/2)] + dp[int(i/3)] + dp[int(i/4)]) , i)
43+
44+
return dp[n]
45+
46+
47+
#{
48+
# Driver Code Starts
49+
#Initial Template for Python 3
50+
51+
if __name__ == '__main__':
52+
t = int(input())
53+
for _ in range(t):
54+
n = int(input())
55+
ob = Solution()
56+
print(ob.maxSum(n))
57+
# } Driver Code Ends

0 commit comments

Comments
 (0)