Search⌘ K
AI Features

Solution: Counting Money

Explore a greedy algorithm solution for the counting money problem by selecting the largest coins first. Learn how this approach works and its time complexity to apply optimization techniques in coding interviews.

Solution: The greedy approach

Caution: This is not the most optimized solution. It only gives you an idea of how the greedy algorithm works.

C#
using System;
using System.Collections.Generic;
class Program
{
/// <summary>
/// This method finds the minimum number of coins needed.
/// </summary>
/// <param name="v">Total amount.</param>
/// <param name="coinsAvailable">Coins available in the machine.</param>
/// <returns>An array of total coins needed.</returns>
public static int[] FindMinCoins(int v, int[] coinsAvailable)
{
// Initialize result
List<int> result = new List<int>();
int n = coinsAvailable.Length;
// Traverse through all available coins
for (int i = n - 1; i >= 0; i--)
{
while (v >= coinsAvailable[i])
{
v -= coinsAvailable[i];
result.Add(coinsAvailable[i]);
}
}
return result.ToArray();
}
// Main program to test the above code
public static void Main(string[] args)
{
int[] coinsAvailable = { 1, 5, 10, 25 }; // The available coins are in increasing order
int[] result = FindMinCoins(19, coinsAvailable);
Console.WriteLine("[" + string.Join(", ", result) + "]");
}
}

Explanation

The simple greedy idea is to start from the largest possible coin available and keep adding coins while the ...