DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Originally published at practice.geeksforgeeks.org

1 1

Maximum Sum Problem GeeksForGeeks

Problem Statement

A number n can be broken into three parts n/2, n/3, and n/4 (consider only the integer part). Each number obtained in this process can be divided further recursively. Find the maximum sum that can be obtained by summing up the divided parts together.
Note: Given number must be divided at least once.

Example 1

Input:
n = 12
Output: 13
Explanation: Break n = 12 in three parts
{12/2, 12/3, 12/4} = {6, 4, 3}, now current
sum is = (6 + 4 + 3) = 13. Further breaking 6,
4 and 3 into parts will produce sum less than
or equal to 6, 4 and 3 respectively.
Enter fullscreen mode Exit fullscreen mode

Solution

//User function Template for Java 
//recursive solution tc : o(3^n) as we are calling recursive function 3 times /2,/3 and /4
//space time complexity is : o(3^n) auxillary space for the stack as their will be 
// 3^n stack space that will be required
/*
class Solution
{
    public int maxSum(int n) 
    { 
        return solve(n);
    } 
    public int solve(int n){
        if(n==1 || n==0) return n;

        int a = n/2;
        int b = n/3;
        int c = n/4;

        return Integer.max(n,
        solve(a)+solve(b)+solve(c)
        );
    }
} */
// optimized solution using dynamic programming memoization top down approach
// time complexity is O(n) as at max there will be n states and dp will traverse those states 
// space complexity will be O(n) for dp and o(n) for stack space;
class Solution
{
    public int maxSum(int n) 
    { 
        int dp[] = new int[1000001];
        Arrays.fill(dp,-1);
        return solve(n,dp);
    } 
    public int solve(int n,int dp[]){
        if(n==1 || n==0) return n;
        if(dp[n]!=-1) return dp[n];
        int a = n/2;
        int b = n/3;
        int c = n/4;

        return dp[n]= Integer.max(n,
        solve(a,dp)+solve(b,dp)+solve(c,dp)
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay