Example 1 — Greedy coin change
Make 63 cents with 25, 10, 5, and 1.
#include <stdio.h>
int main(void) {
int coins[] = {25, 10, 5, 1};
int amount = 63, total = 0;
for (int i = 0; i < 4; i++) {
int n = amount / coins[i];
amount -= n * coins[i];
total += n;
if (n) printf("%d x %d\n", coins[i], n);
}
printf("total coins: %d\n", total);
return 0;
} How It Works
- Two quarters cover 50, leaving 13.
- One dime leaves 3, no nickel fits, and three pennies finish it.
- For this coin set, taking the largest coin first is optimal.
