Last active
December 23, 2023 19:53
-
-
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.
This file contains 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
<?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]) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
amount
-> This is the amount passedcoins
-> 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 amountcoins_cache
-> Exact amount of coins needed, derived fromcoins_used
above.For the example above the output will be
This is interpreted as to make 121, we need 6 (20) coins and 1 (1) coin.