Solve the coin change problem in Java

Solve the coin change problem in Java

 

In this tutorial, we look forward to using dynamic programming to solve one of the most common interview questions "coin change".

Use effective methods in Java to solve the coin change problem

In the dynamic programming method, we use the additional space complexity dp [amount + 1] and store the previous results. We take a coin and start storing the number of coins required to form a certain number (by iteration to the original number). Then, we update dp[i] with the minimum number of coins currently required and the number of coins required to use that particular coin. Then just check if some results reach dp [amount], otherwise return -1 to indicate that it is impossible to make up the amount.

Let's write code for this.

import java.util.*;

public class Main {

    public static void main(String args[]) {
        int coins[] = { 1, 2, 5};
        int amount = 11;

        int dp[] = new int[amount+1];
        dp[0] = 0;

        for(int i = 1; i <= amount; i++){
            dp[i] = amount+1;
        }

        for(int coin : coins){
            for(int amt = 1; amt <= amount ; amt++){
                if(amt >= coin){
                    dp[amt] = Math.min(dp[amt], 1 + dp[amt - coin]);
                }
            }
        }
        int minCoinsReq = dp[amount] != amount+1 ? dp[amount] : -1 ; 

        System.out.println("Minimum Coins required : " + minCoinsReq);
    }
}

 

输出 :
最低硬币要求:3

In the above code, we just created an array to keep the sum of any coin and the minimum number of coins required to reach that coin. Repeating this operation for each coin, we can reach the minimum number of coins required to collect a specific number. Therefore, we reached a solution.

Guess you like

Origin blog.csdn.net/allway2/article/details/115004344