DEV Community


Discussion on: Daily Challenge #262 - No One Likes Spare Change

jurerotar profile image
Jure Rotar • Edited

Since we're looking for the least amount of coins, we sort the array and start looping from the biggest coin value. We check if total amount is higher than our current coin value and if it is, add the coin to the 'purse' and substract the value of the coin from the total amount.

function getChangeAsCoins(array $coins, int $amount): array {
    $numberOfCoins = count($coins);
    $returnedCoins = [];
    for($i = $numberOfCoins - 1; $i >= 0; $i -- ) {
        while($amount >= $coins[$i]) {
            $amount -= $coins[$i];
            $returnedCoins[] = $coins[$i];
    return $returnedCoins;