Last active
November 22, 2023 15:30
-
-
Save luuhq/a916f5a60553f65eb9f7f295a2ab9f43 to your computer and use it in GitHub Desktop.
coins
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
// Input `n`: number of coin_types | |
// Input `X`: the wanted sum | |
int coin_types = { ... }; | |
const int32_t TRASH = 2 << 24; // guaranteed greater than X | |
std::vector<int32_t> coin_count(TRASH, X); | |
for (int x = 1; x <= X; x++) { | |
for (int c = 0; c < n; c++) { | |
int coin = coin_types[c]; | |
if (coin == x) { | |
coin_count[x] = 1; | |
break; | |
} | |
// Cannot use this coin | |
if (coin > x) { | |
continue; | |
} | |
int previous_x = x - coin; | |
int32_t previous_count = coin_count[previous_x]; | |
// Could not construct the sum using this coin | |
if (previous_count == TRASH) { | |
continue; | |
} | |
if (previous_count + 1 < coin_count[x]) { | |
coin_count[x] = previous_count + 1; | |
} | |
} | |
} | |
std::cout << coin_count[X] == TRASH ? -1 : coin_count[X] << std::endl; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment