Open In App

Coin Change – Minimum Coins to Make Sum

Last Updated : 15 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of coins[] of size n and a target value sum, where coins[i] represent the coins of different denominations. You have an infinite supply of each of the coins. The task is to find the minimum number of coins required to make the given value sum. If it’s not possible to make a change, return -1.

Examples:  

Input: coins[] = [25, 10, 5], sum = 30
Output: 2
Explanation : Minimum 2 coins needed, 25 and 5  

Input: coins[] = [9, 6, 5, 1], sum = 19
Output: 3
Explanation: 19 = 9 + 9 + 1

Input: coins[] = [5, 1], sum = 0
Output: 0
Explanation: For 0 sum, we do not need a coin

Input: coins[] = [4, 6, 2], sum = 5
Output: -1
Explanation: Not possible to make the given sum.

Using Recursion – O(n^sum) Time and O(sum) Space

This problem is a variation of the problem Coin Change Problem. Here instead of finding the total number of possible solutions, we need to find the solution with the minimum number of coins.

The idea is to find the minimum number of coins required to reach the target sum by trying each coin denomination in the coins[] array. Starting from the target sum, for each coin coins[i], we can either include it or exclude it. If we include it, we subtract its value from sum and recursively try to make the remaining amount with the same coin denominations. If we exclude it, we move to the next coin in the list.

Mathematically the recurrence relation will look like the following:

minCoins(i, sum, coins) = min(1 + minCoins(i, sum-coins[i], coins), minCoins(i+1, sum, coins))

Base cases:

  • minCoins(i, sum, coins) = 0, if sum = 0.
  • minCoins(i, sum, coins) = INTEGER MAX, if sum < 0 or i == size of coins.
C++
// C++ program to find minimum of coins
// to make a given change sum
#include<bits/stdc++.h>
using namespace std;

int minCoinsRecur(int i, int sum, vector<int> &coins) {
    
    // base case
    if (sum == 0) return 0;
    if (sum <0 || i == coins.size()) return INT_MAX;
    
    int take = INT_MAX;
    
    // take a coin only if its value
    // is greater than 0.
    if (coins[i]>0) {
        take = minCoinsRecur(i, sum-coins[i], coins);
        if (take != INT_MAX) take++;
    }
    
    int noTake = minCoinsRecur(i+1, sum, coins);
    
    return min(take, noTake);
}

int minCoins(vector<int> &coins, int sum) {

   int ans = minCoinsRecur(0, sum, coins);
   return ans!=INT_MAX?ans:-1;
}

int main() {
    vector<int> coins =  {9, 6, 5, 1};
    int sum = 19;
    cout << minCoins(coins, sum);
    return 0;
}
Java
// Java program to find minimum of coins
// to make a given change sum

import java.util.Arrays;

class GfG {

    static int minCoinsRecur(int i, int sum, int[] coins) {
        
        // base case
        if (sum == 0) return 0;
        if (sum < 0 || i == coins.length) return Integer.MAX_VALUE;
        
        int take = Integer.MAX_VALUE;
        
        // take a coin only if its value
        // is greater than 0.
        if (coins[i] > 0) {
            take = minCoinsRecur(i, sum - coins[i], coins);
            if (take != Integer.MAX_VALUE) take++;
        }
        
        int noTake = minCoinsRecur(i + 1, sum, coins);
        
        return Math.min(take, noTake);
    }

    static int minCoins(int[] coins, int sum) {
        int ans = minCoinsRecur(0, sum, coins);
        return ans != Integer.MAX_VALUE ? ans : -1;
    }

    public static void main(String[] args) {
        int[] coins = {9, 6, 5, 1};
        int sum = 19;
        System.out.println(minCoins(coins, sum));
    }
}
Python
# Python program to find minimum of coins
# to make a given change sum

def minCoinsRecur(i, sum, coins):
    
    # base case
    if sum == 0:
        return 0
    if sum < 0 or i == len(coins):
        return float('inf')
    
    take = float('inf')
    
    # take a coin only if its value
    # is greater than 0.
    if coins[i] > 0:
        take = minCoinsRecur(i, sum - coins[i], coins)
        if take != float('inf'):
            take += 1
    
    noTake = minCoinsRecur(i + 1, sum, coins)
    
    return min(take, noTake)

def minCoins(coins, sum):
    ans = minCoinsRecur(0, sum, coins)
    return ans if ans != float('inf') else -1

if __name__ == "__main__":
    coins = [9, 6, 5, 1]
    sum = 19
    print(minCoins(coins, sum))
C#
// C# program to find minimum of coins
// to make a given change sum

using System;

class GfG {

    static int minCoinsRecur(int i, int sum, int[] coins) {
        
        // base case
        if (sum == 0) return 0;
        if (sum < 0 || i == coins.Length) return int.MaxValue;
        
        int take = int.MaxValue;
        
        // take a coin only if its value
        // is greater than 0.
        if (coins[i] > 0) {
            take = minCoinsRecur(i, sum - coins[i], coins);
            if (take != int.MaxValue) take++;
        }
        
        int noTake = minCoinsRecur(i + 1, sum, coins);
        
        return Math.Min(take, noTake);
    }

    static int minCoins(int[] coins, int sum) {
        int ans = minCoinsRecur(0, sum, coins);
        return ans != int.MaxValue ? ans : -1;
    }

    static void Main(string[] args) {
        int[] coins = { 9, 6, 5, 1 };
        int sum = 19;
        Console.WriteLine(minCoins(coins, sum));
    }
}
JavaScript
// JavaScript program to find minimum of coins
// to make a given change sum

function minCoinsRecur(i, sum, coins) {
    
    // base case
    if (sum === 0) return 0;
    if (sum < 0 || i === coins.length) return Number.MAX_VALUE;
    
    let take = Number.MAX_VALUE;
    
    // take a coin only if its value
    // is greater than 0.
    if (coins[i] > 0) {
        take = minCoinsRecur(i, sum - coins[i], coins);
        if (take !== Number.MAX_VALUE) take++;
    }
    
    let noTake = minCoinsRecur(i + 1, sum, coins);
    
    return Math.min(take, noTake);
}

function minCoins(coins, sum) {
    let ans = minCoinsRecur(0, sum, coins);
    return ans !== Number.MAX_VALUE ? ans : -1;
}

const coins = [9, 6, 5, 1];
const sum = 19;
console.log(minCoins(coins, sum));

Output
3

Using Top-Down DP (Memoization) – O(n*sum) Time and O(n*sum) Space

If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:

1. Optimal Substructure:

Minimum number of ways to make sum at index i, i.e., minCoins(i, sum, coins), depends on the optimal solutions of the subproblems minCoins(i, sum-coins[i], coins) , and minCoins(i+1, sum, coins). By comparing these optimal substructures, we can efficiently calculate the minimum number of coins to make target sum at index i.

2. Overlapping Subproblems:

While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times.

  • There are only are two parameters: i and sum that changes in the recursive solution. So we create a 2D matrix of size n*(sum+1) for memoization.
  • We initialize this matrix as -1 to indicate nothing is computed initially.
  • Now we modify our recursive solution to first check if the value is -1, then only make recursive calls. This way, we avoid re-computations of the same subproblems.
C++
// C++ program to find minimum of coins
// to make a given change sum
#include<bits/stdc++.h>
using namespace std;

int minCoinsRecur(int i, int sum, vector<int> &coins, vector<vector<int>> &memo) {

    // base case
    if (sum == 0) return 0;
    if (sum <0 || i == coins.size()) return INT_MAX;
    
    if (memo[i][sum]!=-1) return memo[i][sum];
    
    int take = INT_MAX;
    
    // take a coin only if its value
    // is greater than 0.
    if (coins[i]>0) {
        take = minCoinsRecur(i, sum-coins[i], coins, memo);
        if (take != INT_MAX) take++;
    }
    
    int noTake = minCoinsRecur(i+1, sum, coins, memo);
    
    return memo[i][sum] = min(take, noTake);
}

int minCoins(vector<int> &coins, int sum) {
    vector<vector<int>> memo(coins.size(), vector<int>(sum+1, -1));
    int ans = minCoinsRecur(0, sum, coins, memo);
    return ans!=INT_MAX?ans:-1;
}

int main() {
    vector<int> coins =  {9, 6, 5, 1};
    int sum = 19;
    cout << minCoins(coins, sum);
    return 0;
}
Java
// Java program to find minimum of coins
// to make a given change sum

import java.util.Arrays;

class GfG {

    static int minCoinsRecur(int i, int sum, int[] coins, int[][] memo) {

        // base case
        if (sum == 0) return 0;
        if (sum < 0 || i == coins.length) return Integer.MAX_VALUE;
        
        if (memo[i][sum] != -1) return memo[i][sum];
        
        int take = Integer.MAX_VALUE;
        
        // take a coin only if its value
        // is greater than 0.
        if (coins[i] > 0) {
            take = minCoinsRecur(i, sum - coins[i], coins, memo);
            if (take != Integer.MAX_VALUE) take++;
        }
        
        int noTake = minCoinsRecur(i + 1, sum, coins, memo);
        
        return memo[i][sum] = Math.min(take, noTake);
    }

    static int minCoins(int[] coins, int sum) {
        int[][] memo = new int[coins.length][sum + 1];
        for (int[] row : memo) Arrays.fill(row, -1);
        int ans = minCoinsRecur(0, sum, coins, memo);
        return ans != Integer.MAX_VALUE ? ans : -1;
    }

    public static void main(String[] args) {
        int[] coins = {9, 6, 5, 1};
        int sum = 19;
        System.out.println(minCoins(coins, sum));
    }
}
Python
# Python program to find minimum of coins
# to make a given change sum

def minCoinsRecur(i, sum, coins, memo):
    
    # base case
    if sum == 0:
        return 0
    if sum < 0 or i == len(coins):
        return float('inf')
    
    if memo[i][sum] != -1:
        return memo[i][sum]
    
    take = float('inf')
    
    # take a coin only if its value
    # is greater than 0.
    if coins[i] > 0:
        take = minCoinsRecur(i, sum - coins[i], coins, memo)
        if take != float('inf'):
            take += 1
    
    noTake = minCoinsRecur(i + 1, sum, coins, memo)
    
    memo[i][sum] = min(take, noTake)
    return memo[i][sum]

def minCoins(coins, sum):
    memo = [[-1] * (sum + 1) for _ in range(len(coins))]
    ans = minCoinsRecur(0, sum, coins, memo)
    return ans if ans != float('inf') else -1

if __name__ == "__main__":
    coins = [9, 6, 5, 1]
    sum = 19
    print(minCoins(coins, sum))
C#
// C# program to find minimum of coins
// to make a given change sum

using System;

class GfG {

    static int minCoinsRecur(int i, int sum, int[] coins, int[,] memo) {

        // base case
        if (sum == 0) return 0;
        if (sum < 0 || i == coins.Length) return int.MaxValue;
        
        if (memo[i, sum] != -1) return memo[i, sum];
        
        int take = int.MaxValue;
        
        // take a coin only if its value
        // is greater than 0.
        if (coins[i] > 0) {
            take = minCoinsRecur(i, sum - coins[i], coins, memo);
            if (take != int.MaxValue) take++;
        }
        
        int noTake = minCoinsRecur(i + 1, sum, coins, memo);
        
        memo[i, sum] = Math.Min(take, noTake);
        return memo[i, sum];
    }

    static int minCoins(int[] coins, int sum) {
        int[,] memo = new int[coins.Length, sum + 1];
        for (int i = 0; i < coins.Length; i++)
            for (int j = 0; j <= sum; j++)
                memo[i, j] = -1;
        int ans = minCoinsRecur(0, sum, coins, memo);
        return ans != int.MaxValue ? ans : -1;
    }

    static void Main(string[] args) {
        int[] coins = { 9, 6, 5, 1 };
        int sum = 19;
        Console.WriteLine(minCoins(coins, sum));
    }
}
JavaScript
// JavaScript program to find minimum of coins
// to make a given change sum

function minCoinsRecur(i, sum, coins, memo) {

    // base case
    if (sum === 0) return 0;
    if (sum < 0 || i === coins.length) return Number.MAX_VALUE;
    
    if (memo[i][sum] !== -1) return memo[i][sum];
    
    let take = Number.MAX_VALUE;
    
    // take a coin only if its value
    // is greater than 0.
    if (coins[i] > 0) {
        take = minCoinsRecur(i, sum - coins[i], coins, memo);
        if (take !== Number.MAX_VALUE) take++;
    }
    
    let noTake = minCoinsRecur(i + 1, sum, coins, memo);
    
    memo[i][sum] = Math.min(take, noTake);
    return memo[i][sum];
}

function minCoins(coins, sum) {
    const memo = Array.from({ length: coins.length }, () => Array(sum + 1).fill(-1));
    const ans = minCoinsRecur(0, sum, coins, memo);
    return ans !== Number.MAX_VALUE ? ans : -1;
}

const coins = [9, 6, 5, 1];
const sum = 19;
console.log(minCoins(coins, sum));

Output
3

Using Bottom-Up DP (Tabulation) – O(n*sum) Time and O(n*sum) Space

The idea is to fill the DP table based on previous values. For each coin, we either include it or exclude it to compute the minimum number of coins needed for each sum. The table is filled in an iterative manner from i = n-1 to i = 0 and for each sum from 1 to sum.

The dynamic programming relation is as follows: 

  • if (sum-coins[i]) is greater than 0, then dp[i][sum] = min(1+dp[i][sum-coins[i]], dp[i+1][sum])
  • else dp[i][sum] = dp[i+1][sum].
C++
// C++ program to find minimum of coins
// to make a given change sum
#include<bits/stdc++.h>
using namespace std;

int minCoins(vector<int> &coins, int sum) {
    vector<vector<int>> dp(coins.size(), vector<int>(sum+1, 0));
    
    for (int i=coins.size()-1; i>=0; i--) {
        for (int j=1; j<=sum; j++) {
            dp[i][j] = INT_MAX;
            int take = INT_MAX, noTake = INT_MAX;
            
            // If we take coins[i] coin
            if (j-coins[i]>=0) {
                take = dp[i][j-coins[i]];
                if (take != INT_MAX) take++;
            }
            
            if (i+1<coins.size())
                noTake = dp[i+1][j];
            
            dp[i][j] = min(take, noTake);
        }
    }
    
    if (dp[0][sum]!=INT_MAX) return dp[0][sum];
    return -1;
}

int main() {
    vector<int> coins =  {9, 6, 5, 1};
    int sum = 19;
    cout << minCoins(coins, sum);
    return 0;
}
Java
// Java program to find minimum of coins
// to make a given change sum

import java.util.Arrays;

class GfG {

    static int minCoins(int[] coins, int sum) {
        int[][] dp = new int[coins.length][sum + 1];

        for (int i = coins.length - 1; i >= 0; i--) {
            for (int j = 1; j <= sum; j++) {
                dp[i][j] = Integer.MAX_VALUE;
                int take = Integer.MAX_VALUE, noTake = Integer.MAX_VALUE;

                // If we take coins[i] coin
                if (j - coins[i] >= 0) {
                    take = dp[i][j - coins[i]];
                    if (take != Integer.MAX_VALUE) take++;
                }

                if (i + 1 < coins.length) noTake = dp[i + 1][j];

                dp[i][j] = Math.min(take, noTake);
            }
        }

        if (dp[0][sum] != Integer.MAX_VALUE) return dp[0][sum];
        return -1;
    }

    public static void main(String[] args) {
        int[] coins = {9, 6, 5, 1};
        int sum = 19;
        System.out.println(minCoins(coins, sum));
    }
}
Python
# Python program to find minimum of coins
# to make a given change sum

def minCoins(coins, sum):
    dp = [[0] * (sum + 1) for _ in range(len(coins))]

    for i in range(len(coins) - 1, -1, -1):
        for j in range(1, sum + 1):
            dp[i][j] = float('inf')
            take = float('inf')
            noTake = float('inf')

            # If we take coins[i] coin
            if j - coins[i] >= 0:
                take = dp[i][j - coins[i]]
                if take != float('inf'):
                    take += 1

            if i + 1 < len(coins):
                noTake = dp[i + 1][j]

            dp[i][j] = min(take, noTake)

    if dp[0][sum] != float('inf'):
        return dp[0][sum]
    return -1

if __name__ == "__main__":
    coins = [9, 6, 5, 1]
    sum = 19
    print(minCoins(coins, sum))
C#
// C# program to find minimum of coins
// to make a given change sum

using System;

class GfG {

    static int minCoins(int[] coins, int sum) {
        int[,] dp = new int[coins.Length, sum + 1];

        for (int i = coins.Length - 1; i >= 0; i--) {
            for (int j = 1; j <= sum; j++) {
                dp[i, j] = int.MaxValue;
                int take = int.MaxValue, noTake = int.MaxValue;

                // If we take coins[i] coin
                if (j - coins[i] >= 0) {
                    take = dp[i, j - coins[i]];
                    if (take != int.MaxValue) take++;
                }

                if (i + 1 < coins.Length) noTake = dp[i + 1, j];

                dp[i, j] = Math.Min(take, noTake);
            }
        }

        if (dp[0, sum] != int.MaxValue) return dp[0, sum];
        return -1;
    }

    static void Main(string[] args) {
        int[] coins = { 9, 6, 5, 1 };
        int sum = 19;
        Console.WriteLine(minCoins(coins, sum));
    }
}
JavaScript
// JavaScript program to find minimum of coins
// to make a given change sum

function minCoins(coins, sum) {
    let dp = Array.from({ length: coins.length }, () => Array(sum + 1).fill(0));

    for (let i = coins.length - 1; i >= 0; i--) {
        for (let j = 1; j <= sum; j++) {
            dp[i][j] = Number.MAX_VALUE;
            let take = Number.MAX_VALUE, noTake = Number.MAX_VALUE;

            // If we take coins[i] coin
            if (j - coins[i] >= 0) {
                take = dp[i][j - coins[i]];
                if (take !== Number.MAX_VALUE) take++;
            }

            if (i + 1 < coins.length) noTake = dp[i + 1][j];

            dp[i][j] = Math.min(take, noTake);
        }
    }

    if (dp[0][sum] !== Number.MAX_VALUE) return dp[0][sum];
    return -1;
}

const coins = [9, 6, 5, 1];
const sum = 19;
console.log(minCoins(coins, sum));

Output
3

Using Space Optimized DP – O(n*sum) Time and O(sum) Space

In previous approach of dynamic programming we have derive the relation between states as given below:

  • if (sum-coins[i]) is greater than 0, then dp[i][sum] = min(1+dp[i][sum-coins[i]], dp[i+1][sum])
  • else dp[i][sum] = dp[i+1][sum].

If we observe that for calculating current dp[i][sum] state we only need previous row dp[i-1][sum] or current row dp[i][sum-coins[i]]. There is no need to store all the previous states just one previous state is used to compute result.

C++
// C++ program to find minimum of coins
// to make a given change sum
#include<bits/stdc++.h>
using namespace std;

int minCoins(vector<int> &coins, int sum) {
    vector<int> dp(sum+1, INT_MAX);
    dp[0] = 0;
    
    for (int i=coins.size()-1; i>=0; i--) {
        for (int j=1; j<=sum; j++) {
            
            int take = INT_MAX, noTake = INT_MAX;
            
            // If we take coins[i] coin
            if (j-coins[i]>=0 && coins[i]>0) {
                take = dp[j-coins[i]];
                if (take != INT_MAX) take++;
            }
            
            if (i+1<coins.size())
                noTake = dp[j];
            
            dp[j] = min(take, noTake);
        }
    }
    
    if (dp[sum]!=INT_MAX) return dp[sum];
    return -1;
}

int main() {
    vector<int> coins =  {9, 6, 5, 1};
    int sum = 19;
    cout << minCoins(coins, sum);
    return 0;
}
Java
// Java program to find minimum of coins
// to make a given change sum
import java.util.Arrays;

class GfG {

    static int minCoins(int[] coins, int sum) {
        int[] dp = new int[sum + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;

        for (int i = coins.length - 1; i >= 0; i--) {
            for (int j = 1; j <= sum; j++) {
                int take = Integer.MAX_VALUE, noTake = Integer.MAX_VALUE;

                // If we take coins[i] coin
                if (j - coins[i] >= 0 && coins[i] > 0) {
                    take = dp[j - coins[i]];
                    if (take != Integer.MAX_VALUE) take++;
                }

                if (i + 1 < coins.length)
                    noTake = dp[j];

                dp[j] = Math.min(take, noTake);
            }
        }

        if (dp[sum] != Integer.MAX_VALUE) return dp[sum];
        return -1;
    }

    public static void main(String[] args) {
        int[] coins = {9, 6, 5, 1};
        int sum = 19;
        System.out.println(minCoins(coins, sum));
    }
}
Python
# Python program to find minimum of coins
# to make a given change sum

def minCoins(coins, sum):
    dp = [float('inf')] * (sum + 1)
    dp[0] = 0

    for i in range(len(coins) - 1, -1, -1):
        for j in range(1, sum + 1):
            take = float('inf')
            noTake = float('inf')

            # If we take coins[i] coin
            if j - coins[i] >= 0 and coins[i] > 0:
                take = dp[j - coins[i]]
                if take != float('inf'):
                    take += 1

            if i + 1 < len(coins):
                noTake = dp[j]

            dp[j] = min(take, noTake)

    return dp[sum] if dp[sum] != float('inf') else -1

if __name__ == "__main__":
    coins = [9, 6, 5, 1]
    sum = 19
    print(minCoins(coins, sum))
C#
// C# program to find minimum of coins
// to make a given change sum
using System;

class GfG {

    static int minCoins(int[] coins, int sum) {
        int[] dp = new int[sum + 1];
        Array.Fill(dp, int.MaxValue);
        dp[0] = 0;

        for (int i = coins.Length - 1; i >= 0; i--) {
            for (int j = 1; j <= sum; j++) {
                int take = int.MaxValue, noTake = int.MaxValue;

                // If we take coins[i] coin
                if (j - coins[i] >= 0 && coins[i] > 0) {
                    take = dp[j - coins[i]];
                    if (take != int.MaxValue) take++;
                }

                if (i + 1 < coins.Length)
                    noTake = dp[j];

                dp[j] = Math.Min(take, noTake);
            }
        }

        if (dp[sum] != int.MaxValue) return dp[sum];
        return -1;
    }

    static void Main() {
        int[] coins = { 9, 6, 5, 1 };
        int sum = 19;
        Console.WriteLine(minCoins(coins, sum));
    }
}
JavaScript
// JavaScript program to find minimum of coins
// to make a given change sum

function minCoins(coins, sum) {
    let dp = new Array(sum + 1).fill(Number.MAX_VALUE);
    dp[0] = 0;

    for (let i = coins.length - 1; i >= 0; i--) {
        for (let j = 1; j <= sum; j++) {
            let take = Number.MAX_VALUE, noTake = Number.MAX_VALUE;

            // If we take coins[i] coin
            if (j - coins[i] >= 0 && coins[i] > 0) {
                take = dp[j - coins[i]];
                if (take !== Number.MAX_VALUE) take++;
            }

            if (i + 1 < coins.length)
                noTake = dp[j];

            dp[j] = Math.min(take, noTake);
        }
    }

    return dp[sum] !== Number.MAX_VALUE ? dp[sum] : -1;
}

let coins = [9, 6, 5, 1];
let sum = 19;
console.log(minCoins(coins, sum));

Output
3


Next Article

Similar Reads

three90RightbarBannerImg
  翻译: