Skip to content

Instantly share code, notes, and snippets.

@Ghostscypher
Last active December 23, 2023 19:53
Show Gist options
  • Save Ghostscypher/07dea582fd8d4ad547fc22ec9cb0236e to your computer and use it in GitHub Desktop.
Save Ghostscypher/07dea582fd8d4ad547fc22ec9cb0236e to your computer and use it in GitHub Desktop.
This is a quick code for min number of coins problem, solved using dynamic programming.
<?php
function min_coins($m, $coins)
{
// Use memoization to avoid repeated calculations
$memo = [];
$memo[0] = 0;
for($i = 1; $i <= $m; $i++)
{
foreach($coins as $coin)
{
$diff = $i - $coin;
if($diff < 0)
{
break;
}
if($diff >= 0 && isset($memo[$diff]))
{
$memo[$i] = min($memo[$i] ?? INF, $memo[$diff] + 1);
// dump($memo[$i]);
}
}
}
// To get the coins used to make up the amount, we can use the following code
$coins_used = array_filter($coins, function($coin) use ($memo, $m) {
return isset($memo[$m - $coin]) && $memo[$m - $coin] + 1 == $memo[$m];
});
// This will be used to cache the coins used to make up the amount
$coins_cache = [];
$m_copy = $m;
foreach($coins_used as $coin)
{
while($m > 0 && isset($memo[$m]) && $memo[$m] == $memo[$m - $coin] + 1)
{
$coins_cache[$coin][] = $coin;
$m -= $coin;
}
}
// If the amount is not possible to make up with the given coins return -1
return [
'amount' => $m_copy,
'coins' => $memo[$m_copy] ?? -1,
'coins_used' => $coins_used,
'coins_cache' => $coins_cache,
];
}
print_r(
min_coins(121, [1, 5, 10, 20])
);
@Ghostscypher
Copy link
Author

amount -> This is the amount passed
coins -> Number of coins required to return the amount -1 if a solution doesn't exist.
coins_used -> Refers to the coins that are used to make the amount
coins_cache -> Exact amount of coins needed, derived from coins_used above.

For the example above the output will be

Array
(
    [amount] => 121
    [coins] => 7
    [coins_used] => Array
        (
            [0] => 1
            [3] => 20
        )

    [coins_cache] => Array
        (
            [1] => Array
                (
                    [0] => 1
                )

            [20] => Array
                (
                    [0] => 20
                    [1] => 20
                    [2] => 20
                    [3] => 20
                    [4] => 20
                    [5] => 20
                )

        )

)

This is interpreted as to make 121, we need 6 (20) coins and 1 (1) coin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment