- array_merge: documentation ( source)
- json_encode: documentation ( source)
- range: documentation ( source)
- printf: documentation ( source)
<?php
function optimalChange(int $amount, array $denominations): ?array {
if (!$amount) {
return []; // happy ending
}
foreach ($denominations as $d) {
if ($d <= $amount) {
$deeper = optimalChange($amount - $d, $denominations);
if ($deeper !== null) {
$result = array_merge([$d], $deeper);
break; // run up the recursive branch
}
}
}
return $result ?? null;
}
$target = 23;
$denominations = [10, 5, 2]; // must be rsort()ed at declaration
foreach (range(0, 35) as $target) {
printf(
"%s: %s\n",
$target,
json_encode(
optimalChange($target, $denominations)
?: 'Sorry'
)
);
}