DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Edited on

1

Coin Change 2 Leetcode

Problem

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.

You may assume that you have an infinite number of each kind of coin.

The answer is guaranteed to fit into a signed 32-bit integer.

Example 1:

Input: amount = 5, coins = [1,2,5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
Enter fullscreen mode Exit fullscreen mode
class Solution {
    public long count(int coins[], int N, int sum) {
        // code here.
        long dp[][] = new long[N][sum+1];
        for(long d[] : dp) Arrays.fill(d,-1);
        return count(0,coins,sum,dp);
    }
    public long count (int i, int coins[], int sum,long dp[][]){
        //base case
        if(sum ==0) return 1;
        if(i == coins.length-1){
            if(sum%coins[i]==0) return 1;
            return 0;
        }

        if(dp[i][sum]!=-1) return dp[i][sum];

        long take = 0;
        if(sum>=coins[i]){
            take = count(i,coins,sum-coins[i],dp);
        }
        long dontTake = count(i+1,coins,sum,dp);

        return dp[i][sum] =  take+dontTake;
    }
}
Enter fullscreen mode Exit fullscreen mode

We can remove the stack space by using tabulation approach of dp

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.