The Wayback Machine - https://web.archive.org/web/20241122234704/https://www.geeksforgeeks.org/find-minimum-number-of-coins-that-make-a-change/
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


Previous Article
Next Article

Similar Reads

Minimum cost for acquiring all coins with k extra coins allowed with every coin
You are given a list of N coins of different denominations. You can pay an amount equivalent to any 1 coin and can acquire that coin. In addition, once you have paid for a coin, we can choose at most K more coins and can acquire those for free. The task is to find the minimum amount required to acquire all the N coins for a given value of K. Exampl
11 min read
Check if two piles of coins can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other
Given two piles of coins consisting of N and M coins, the task is to check if both the piles can be emptied simultaneously by repeatedly removing 2 coins from one pile and 1 coin from the other pile. If both the piles can be made empty, then print "Yes". Otherwise, print "No". Examples: Input: N = 1, M = 2 Output: Yes Explanation: Remove 1 coin fro
6 min read
Coin change problem with limited coins
Given three integers n, k, target, and an array of coins[] of size n. Find if it is possible to make a change of target cents by using an infinite supply of each coin but the total number of coins used must be exactly equal to k. Examples: Input: n = 5, k = 3, target = 11, coins = {1, 10, 5, 8, 6}Output: 1Explanation: 2 coins of 5 and 1 coin of 1 c
12 min read
Make a fair coin from a biased coin
You are given a function foo() that represents a biased coin. When foo() is called, it returns 0 with 60% probability, and 1 with 40% probability. Write a new function that returns 0 and 1 with a 50% probability each. Your function should use only foo(), no other library method. Solution: We know foo() returns 0 with 60% probability. How can we ens
6 min read
Coin Change - Count Ways to Make Sum
Given an integer array of coins[] of size n representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = [1, 2, 3]Output: 4Explanation: There are four solutions: [1, 1
15+ min read
Decision Trees - Fake (Counterfeit) Coin Puzzle (12 Coin Puzzle)
Let us solve the classic "fake coin" puzzle using decision trees. There are the two different variants of the puzzle given below. I am providing description of both the puzzles below, try to solve on your own, assume N = 8. Easy: Given a two pan fair balance and N identically looking coins, out of which only one coin is lighter (or heavier). To fig
12 min read
Probability of getting two consecutive heads after choosing a random coin among two different types of coins
Given two coins which have probability of getting heads p% and q% respectively, the task is to determine the probability of getting two consecutive heads after choosing random coins among the given coins.Examples: Input: p = 33, q = 66 Output: 0.550000000000000Input: p = 33, q = 66 Output: 0.550000000000000 Approach: Since both the coins are not id
5 min read
Maximize value of coins when coins from adjacent row and columns cannot be collected
Given a 2D array arr[][] of size N * M, the value in arr[][] represents the value of coins, the task is to maximize the value of collected coins when during collecting the coins from the arr[][], all the coins from the adjacent row (i.e, i - 1 and i + 1) will disappear, and coins at the adjacent column (i.e arr[i][j + 1] and arr[i][j - 1]) will als
9 min read
Buy minimum items without change and given coins
You have an unlimited number of 10-rupee coins and exactly one coin of r rupee and you need to buy minimum items each of cost k such that you do not ask for change.Examples: Input: k = 15, r = 2 Output: 2 You should buy two cables and pay 2*15=30 rupees. It is obvious that you can pay this sum without any change.Input: k = 237, r = 7 Output:1 It is
4 min read
Coin Change | BFS Approach
Given an integer X and an array arr[] of length N consisting of positive integers, the task is to pick minimum number of integers from the array such that they sum up to N. Any number can be chosen infinite number of times. If no answer exists then print -1.Examples: Input: X = 7, arr[] = {3, 5, 4} Output: 2 The minimum number elements will be 2 as
6 min read
Minimum moves taken to move coin of each cell to any one cell of Matrix
Given an odd number N which represents a grid of size N x N which is initially filled by coins, the task is to find the minimum number of moves required for all the coins to move to any cell of the grid such that in each step, some arbitrary coin in the middle of the grid can move to any of the surrounding eight cells. Examples: Input: N = 3 Output
6 min read
Maximum coin in minimum time by skipping K obstacles along path in Matrix
Given a 2D matrix, where '*' represents an obstacle and the rest all represent coins in the grid. It is also given that you are currently on grid[i1][ j1] and want to reach grid[i2][j2] by skipping at most K obstacles in the path, the task is to collect the maximum coin while reaching grid[i2][j2] in a minimum amount of time. Note: Only movements i
14 min read
Minimum number of coins that can generate all the values in the given range
Given an integer N, the task is to find the minimum number of coins required to create all the values in the range [1, N]. Examples: Input: N = 5Output: 3The coins {1, 2, 4} can be used to generate all the values in the range [1, 5].1 = 12 = 23 = 1 + 24 = 45 = 1 + 4 Input: N = 10Output: 4 Approach: The problem is a variation of coin change problem,
6 min read
Minimum number of coins having value equal to powers of 2 required to obtain N
Given an integer N, the task is to find the minimum number of coins of the form 2i required to make a change for N cents. Examples: Input: N = 5 Output: 2 Explanation: Possible values of coins are: {1, 2, 4, 8, ...} Possible ways to make change for N cents are as follows: 5 = 1 + 1 + 1 + 1 + 1 5 = 1 + 2 + 2 5 = 1 + 4 (Minimum) Therefore, the requir
4 min read
Minimum number of coins to be collected per hour to empty N piles in at most H hours
Given an array arr[] consisting of N integers representing the number of coins in each pile, and an integer H, the task is to find the minimum number of coins that must be collected from a single pile per hour such that all the piles are emptied in less than H hours. Note: Coins can be collected only from a single pile in an hour. Examples: Input:
8 min read
Minimum number of coins needed to remove all the elements of the array based on given rules
Given an array arr of length N with values 1 and 2 indicating type 1 and type 2 elements and two players, player1 and player2. The task is to find the minimum number of coins required to remove all the elements in the order given in the array. Below rules must be followed: Player1 and Player2 take turns removing elements with Player1 starting first
9 min read
Find out the minimum number of coins required to pay total amount
Given a total amount of N and unlimited number of coins worth 1, 10 and 25 currency coins. Find out the minimum number of coins you need to use to pay exactly amount N.Examples: Input : N = 14Output : 5You will use one coin of value 10 and four coins of value 1.Input : N = 88Output : 7 Approach: To solve this problem we will use recursion to try al
11 min read
Minimum removal of people to equalize the number of coins
Given an array X[] of length N. This denotes that ith person has X[i] coins, the task is to output the minimum number of people needed to remove so that, the remaining person will have an equal number of coins. While removing ith person, the below operations will take place, consider that he has X[i] coins, then: That ith person will be removed fro
7 min read
Minimum distance to collect coins and place them in House
Given an m*n matrix that contains character 'B' to represent the boy's initial position, 'H' represents the house's position, 'C' represents the position of coins, and '.' represents empty cells, the task is to find the minimum distance (i.e. minimum moves) for the boy to collect all the coins and place them inside the house one by one. The boy can
8 min read
Minimum Number of Coins in a Bag
Given an array arr[] where each element represents the number of coins in the bag, also given an integer k, minimize the maximum number of coins present in any bag using at most k operations, In each operation the coins in one bag can be distributed into two bags. Examples: Input: arr[] = [9], k = 2 Output: 3Explanation: Divide the bag with 9 coins
9 min read
Greedy Algorithm to find Minimum number of Coins
Given a value of V Rs and an infinite supply of each of the denominations {1, 2, 5, 10, 20, 50, 100, 500, 1000} valued coins/notes, The task is to find the minimum number of coins and/or notes needed to make the change? Examples: Input: V = 70Output: 2Explanation: We need a 50 Rs note and a 20 Rs note. Input: V = 121Output: 3Explanation: We need a
12 min read
Collect all coins in minimum number of steps
Given many stacks of coins which are arranged adjacently. We need to collect all these coins in the minimum number of steps where in one step we can collect one horizontal line of coins or vertical line of coins and collected coins should be continuous.Examples : Input : height[] = [2 1 2 5 1] Each value of this array corresponds to the height of s
8 min read
Remove Minimum coins such that absolute difference between any two piles is less than K
Given an array, arr[] of size N and an integer K which means there are N piles of coins and the ith contains arr[i] coins. The task is to adjust the number of coins in each pile such that for any two piles if a be the number of coins in the first pile and b be the number of coins in the second pile then |a - b| <= K. One can remove coins from di
7 min read
Find Minimum Number of Coins for Fruits II
Given a 1-indexed array prices[], where prices[i] represents the cost of the ith fruit in a store. The store has a special offer: if you buy the ith fruit for prices[i] coins, you can get the next i fruit for free. Note: Even if you can get an fruit j for free, you still have the option to purchase it for prices[j] coins to receive a new offer. The
7 min read
CSES Solutions - Missing Coin Sum
You have N coins with positive integer values. What is the smallest sum you cannot create using a subset of the coins? Examples: Input: N = 5, coins[] = {2, 9, 1, 2, 7}Output: 6Explanation: Sum = 1, we can take the coin with value 1.Sum = 2, we can take the coin with value 2.Sum = 3, we can take coins with value 1 and 2.Sum = 4, we can take coins w
6 min read
Fixed Coins for Target Sum with Constraint K
Given a set of coin denominations the total number of coins (n) and a target amount (target), the task is to determine if it's possible to make change, for the target amount using k coins. You have one supply of each coin denomination. Examples: Input: n = 4, k = 2, Target = 9, Coins [2, 3, 5, 7]Output: TrueExplanation: In this scenario, you have f
9 min read
Coin game of two corners (Greedy Approach)
Consider a two-player coin game where each player gets turned one by one. There is a row of even a number of coins, and a player on his/her turn can pick a coin from any of the two corners of the row. The player that collects coins with more value wins the game. Develop a strategy for the player making the first turn, such that he/she never loses t
9 min read
Predict the winner in Coin Game
There are two players P1 and P2 and two piles of coins consisting of M and N coins respectively. At each turn, a player can choose only one of the piles out of these and discard the other one. This discarded pile cannot be used further in the game. The pile player chooses is further divided into two piles of non-zero parts. The player who cannot di
4 min read
Find the player who will win the Coin game
Given N coins, the task is to find who win the coin game.Coin game is a game in which each player picks coins from the given N coins in such a way that he can pick coins ranging from 1 to 5 coins in one turn and the game continues for both the players. The player who picks the last coin loses the game.Examples: Input: N = 4 Output: First Player Exp
4 min read
Probability of not getting two consecutive heads together in N tosses of coin
Given a fair coin that is tossed N times, the task is to determine the probability such that no two heads occur consecutively. Examples: Input: N = 2 Output: 0.75 Explanation: When the coin is tossed 2 times, the possible outcomes are {TH, HT, TT, HH}. Since in 3 out of 4 outcomes, heads don't occur together. Therefore, the required probability is
8 min read
three90RightbarBannerImg