Skip to content

Instantly share code, notes, and snippets.

@jimexist
Created October 1, 2014 23:33
Show Gist options
  • Select an option

  • Save jimexist/fac8b03e9f46f0c05fcd to your computer and use it in GitHub Desktop.

Select an option

Save jimexist/fac8b03e9f46f0c05fcd to your computer and use it in GitHub Desktop.
Coin.c - minimal number of coins to get to a target amount
#include <stdio.h>
#include <stdlib.h>
int intcmp(const void *a, const void *b) {
return *((int *)a) - *((int *)b);
}
int min_coins(int coins[], size_t ncoins, int target) {
if (ncoins <=0 ) return 0;
qsort(coins, ncoins, sizeof(int), &intcmp);
int *cache = (int *) malloc(sizeof(int) * (1 + target));
for (int i=0; i<=target; ++i) {
cache[i] = target + 1;
}
cache[0] = 0;
for (int i=0; i<ncoins; ++i) {
int c = coins[i];
for (int j=0; j + c < target + 1; ++j) {
if (cache[j] + 1 < cache[j + c]) {
cache[j + c] = cache[j] + 1;
}
}
}
int result = cache[target];
free(cache);
return result == target + 1 ? -1 : target;
}
int main(int argc, char** argv) {
if (argc < 2) return 0;
int *result = (int*) malloc(sizeof(int) * argc - 2);
int target = atoi(argv[1]);
for (int i=2; i<argc; ++i) {
result[i-2] = atoi(argv[i]);
}
printf("result is: %d\n", min_coins(result, argc-2, target));
free(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment