top of page
Caută
Poza scriitoruluioanaunciuleanu

Find the minimum number of coins that make a given value in JAVA

Given a certain amount of money that we have, we want to change the money into coins. What is the minimum number of coins required to make the change?


Input: int[] coins = {10, 5, 2, 1}; int amount = 12; Output: 2 Explanation: Minimum there are required 2 coins: 10 and 2.


Solution:


1. static int minimumAmountOfCoins(int[] coins, int amount) { 2. int[] minimumAmountOfCoins = new int[amount + 1]; 3. 4. for (int i = 1; i <= amount; i++) { 5. minimumAmountOfCoins[i] = Integer.MAX_VALUE; 6. } 7. 8. for (int i = 1; i <= amount; i++) { 9. for (int coin : coins) 10. if (coin <= i) { 11. int minimumAmountOfCoin = minimumAmountOfCoins[i - coin]; 12. if (minimumAmountOfCoin != Integer.MAX_VALUE && minimumAmountOfCoin + 1 < minimumAmountOfCoins[i]) { 13. minimumAmountOfCoins[i] = minimumAmountOfCoin + 1; 14. } 15. } 16. } 17. 18. if (minimumAmountOfCoins[amount] == Integer.MAX_VALUE) { 19. return -1; 20. } 21. 22. return minimumAmountOfCoins[amount]; 23. } 24.

4 afișări0 comentarii

Postări recente

Afișează-le pe toate

Weighted Job Scheduling in JAVA

You receive a list of jobs that have three elements: start time, finish time and profit. You have to schedule the jobs with no...

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed...

Comments


bottom of page