data-structures · intermediate · ~15 min
Find the minimum number of coins that sum to an amount.
Implement:
int min_coins(const int *coins, int nc, int amount);
Return the fewest coins (unlimited supply of each) that sum exactly to amount, or -1 if impossible.
coins (positive), nc, and a non-negative amount.
Fewest coins, or -1.
amount up to ~10000.
#include <stddef.h>
/* Fewest coins that sum to amount using coins[0..nc-1] (unlimited each); -1 if impossible. amount>=0, coins positive. */
int min_coins(const int *coins,int nc,int amount){ (void)coins;(void)nc;(void)amount; return -1; }
Greedy fails for arbitrary denominations — you need DP over every amount.
amount 0 needs 0 coins; unreachable amounts return -1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.