Last active
April 12, 2016 22:00
-
-
Save ahmedengu/2be31777380e0236a3ace8e9d8f207e0 to your computer and use it in GitHub Desktop.
Write the pseudocode of the greedy algorithm for the change-making problem, with an amount n and coin denominations d1, d2, …, dn as its input. What is the time efficiency class of your algorithm?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Comparator; | |
import java.util.TreeSet; | |
public class ChangeMaking { | |
static TreeSet<Integer> coins = new TreeSet<>(Comparator.reverseOrder()); | |
static int amount = 126; | |
public static void main(String[] args) { | |
coins.add(50); | |
coins.add(25); | |
coins.add(10); | |
coins.add(5); | |
coins.add(1); | |
for (int d : | |
coins) { | |
if (amount - d >= 0) { | |
double tmp = Math.floor(amount / d); | |
System.out.println("amount: " + amount + " coin: " + d + " * " + tmp + " = " + d * tmp); | |
amount -= d * tmp; | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
amount: 126 coin: 50 * 2.0 = 100.0 | |
amount: 26 coin: 25 * 1.0 = 25.0 | |
amount: 1 coin: 1 * 1.0 = 1.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment