Coin Change Problem in java

Table of Contents

If you want to practice data structure and algorithm programs, you can go through Java coding interview questions.

In this post, we will see about Coin Change problem in java.


Problem

Given an Amount to be paid and the currencies to pay with. There is infinite supply of every currency using combination of which, the given amount is to be paid.
Print the number of ways by which the amount can be paid.

INPUT:
currencies = {2,3,4}
amount = 8

OUTPUT:
2, 2, 2, 2,
2, 2, 4,
2, 3, 3,
4, 4,
Number of ways we can pay using given currencies are : 4

Since we are talking about combinations, therefore, order of payments does not matter, that is, [2, 3, 3], [3, 2, 3], [3, 3, 2] all the ways involving same frequency of currencies will be considered as one way.


Solution

Recursive Approach:

In this approach, we will make a recursive call subtracting all the currencies one by one in a loop, that is,

    • we will subtract the currency on the current index from the amount to be paid and make the recursive call for the remaining amount to be paid.
    • We keep a string which keeps track of all the payments made so far, and whenever any call is made, we just concatenate the paid currency in the string.
    • Once we reach to a point where the amount to be paid is zero, this becomes our basecase and we print the payments made so far string and return one as this is one way we can pay the required amount.
    • If the amount left to be paid become negative, this means that we do not have a perfect combination of coins perfectly adding upto the amount to be paid, therefore it is not a way to pay, hence we return zero from this type of basecase.
    • While we make call, we need to make sure that we do not make a payment with a currency having index lower than the current index, as this will lead to the duplications in the combination which we do not want. Therefore, whenever we make calls in loop we initialise our loop variable with the current currency index not from 0th index.
    • As at every stage of the amount to be paid, we are making {number of currencies – current index} number of calls, Say n.
      And the initial amount to be paid = x,
      then the worst time complexity of this algorithm is x^n.
    Consider the following recursion tree for testcase : Amount = 8, Currencies = [2,4]

    Coin Change

    EFFICIENT APPROACH:

    Consider the recursion tree above,

    • We can clearly see duplication of calls, where result of amount = 4 and amount = 2 are being calculated again and again that is, there is an overlap in most of the subproblems which is increasing the complexity of the algorithm.
    • Also, we can see the result for bigger subproblem is being calculated in post order, that is, after we get the result for the smaller subproblems, the result for bigger subproblem is addition of all its child that is, smaller subproblems.
    • As this problem has both the properties of Dynamic Programming, which are Overlapping subproblems and Optimal Substructure. Therefore, we will adopt a Dynamic Programming approach to reduce the worst time complexity of the solution.

    Algorithm:

    • We make an Array to store the result of smaller subproblems, say dp, of size amount + 1,
      because at ith index we store the number of ways to pay an amount = i, so for the having an index ‘amount’ we need to make an array of amount + 1 size.
    • We basically process this array for every currency, that is, for every currency we run a loop over the dp array to calculate the total number of ways to pay the amount with number of currencies = current currency index + 1.
    • The point to understand for understanding this algorithm is that,
      if current amount – current currency can be paid using this currency then, current amount can also be paid, that is, if (dp[amt – currency]) >= 1 then (dp[amt]++)
    • So for every currency at every amount we just need to check if the amount-currency is greater than one that is, if it can be paid. If no, then this amount also cant be paid with the current set of currencies.
    • Now as for every currency we are processing every amount ranging from 0 to given amount,
      Hence the worst time complexity of this approach would be O(amount * num_currencies)
    That’s all about Coin change problem in java.

Related Posts

  • Maximum number of vowels in a Substring of given length
    18 June

    Maximum Number of Vowels in a Substring of Given Length

    Table of ContentsApproach – 1 Generate All Substrings Using substring() MethodApproach – 2 Using Sliding Window Method (Linear Time Solution) In this article, we will look at an interesting problem related to the Strings and [Sliding-Window Algorithm](https://java2blog.com/sliding-window-maximum-java/ “Sliding-Window Algorithm”). The problem is : "Given a String we have to Find the Maximum Number of Vowel […]

  • Find first and last position of element in sorted array
    04 June

    Search for a range Leetcode – Find first and last position of element in sorted array

    Table of ContentsApproach 1 (Using Linear Search)Approach 2 (Using Modified Binary Search-Optimal) In this article, we will look into an interesting problem asked in Coding Interviews related to Searching Algorithms. The problem is: Given a Sorted Array, we need to find the first and last position of an element in Sorted array. This problem is […]

  • 30 April

    Convert Postfix to Infix in Java

    Learn about how to convert Postfix to Infix in java.

  • Prefix to postfix in java
    30 April

    Convert Prefix to Postfix in Java

    Learn about how to convert Prefix to Postfix in java.

  • Data structures in java
    16 April

    Data Structures in java

    Table of ContentsArray Declare and initialize array in javaAdvantages of arrayDisadvantages of array ExampleArray practice programsStackStack implementation using ArrayStack implementation using LinkedListImplementationPractice ProgramsQueueQueue implementation using arrayQueue implementation using LinkedListImplementationLinkedListImplementationLinkedList Practice ProgramsBinary treeImplementationBinary tree practice programsBinary Search treeImplementationBinary search tree Practice programsTrieImplementationHeapImplementationGraphImplementation Inbuild data structures in javaStringHashMapLinkedHashMapArrayListLinkedListHashSet In this post, we will see about various data […]

  • 29 November

    Top 100+ Java coding interview questions

    Table of ContentsStringQuestion 1 : How to reverse a String in java? Can you write a program without using any java inbuilt methods?Question 2 : Write a java program to check if two Strings are anagram in java?Question 3 : Write a program to check if String has all unique characters in java?Question 4 : […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.