Skip to content

Instantly share code, notes, and snippets.

@XedinUnknown
Created August 20, 2018 12:56
Show Gist options
  • Save XedinUnknown/3f13deb54c8ad63a13188636ea631639 to your computer and use it in GitHub Desktop.
Save XedinUnknown/3f13deb54c8ad63a13188636ea631639 to your computer and use it in GitHub Desktop.
Coin Change Problem
function count_change ($money, $coins) {
sort($coins, SORT_NUMERIC);
$money = (int) $money;
$ways = array(); // ['denom' => [ 'value' => 'numWays' ]]
foreach ($coins as $_c => $_denom) {
for ($_m = 0; $_m <= $money; $_m++) {
if ($_m === 0) {
$ways[$_c][$_m] = 1;
continue;
}
if ($_m < $_denom) {
$numWays = isset($ways[$_c-1])
? $ways[$_c-1][$_m]
: 0;
$ways[$_c][$_m] = $numWays;
continue;
}
$prevVal = $ways[$_c][$_m-$_denom];
$prevDenom = $ways[$_c-1][$_m];
$numWays = $prevVal + $prevDenom;
$ways[$_c][$_m] = $numWays;
}
}
return $ways[$_c][$money];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment