Skip to content

Instantly share code, notes, and snippets.

@nichtemna
Created August 11, 2016 14:08
Show Gist options
  • Save nichtemna/27b83437d3289bec62b6331ac634c0b8 to your computer and use it in GitHub Desktop.
Save nichtemna/27b83437d3289bec62b6331ac634c0b8 to your computer and use it in GitHub Desktop.
Minimum number of coins needed to change the input value into coins with denominations 1, 5, and 10.
import java.util.Scanner;
/**
* Created by root on 11.08.16.
*/
public class GreedyCoins {
public static void main(String[] args) {
Scanner scaner = new Scanner(System.in);
int m = scaner.nextInt();
if (m < 1 || m > Math.pow(10, 3)) {
System.out.println("1 <= m <= 10 ^ 3");
} else {
int count = getCount(m);
System.out.println(count);
}
}
private static int getCount(int m) {
int[] coins = new int[]{10, 5, 1};
int count = 0;
int leftCoins = m;
for (int i = 0; i < coins.length; i++) {
int coin = coins[i];
if (leftCoins == 0) {
break;
}
int fit = leftCoins / coin;
count += fit;
leftCoins -= coin * fit;
}
return count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment