3v4l.org

run code in 300+ PHP versions simultaneously
<?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' ) ); }

preferences:
25.39 ms | 407 KiB | 5 Q