Find the least number of coins required that can make any change from 1 to 99 cents

后端 未结 27 2238
生来不讨喜
生来不讨喜 2020-12-07 10:08

Recently I challenged my co-worker to write an algorithm to solve this problem:

Find the least number of coins required that can make any change from

27条回答
  •  心在旅途
    2020-12-07 10:39

    Here's a simple c# solution using Linq.

    internal class Program
    {
        public static IEnumerable Coins = new List
        {
            new Coin {Name = "Dime", Value = 10},
            new Coin {Name = "Penny", Value = 1},
            new Coin {Name = "Nickel", Value = 5},
            new Coin {Name = "Quarter", Value = 25}
        };
        private static void Main(string[] args)
        {
            PrintChange(34);
            Console.ReadKey();
        }
        public static void PrintChange(int amount)
        {
            decimal remaining = amount;
            //Order coins by value in descending order
            var coinsDescending = Coins.OrderByDescending(v => v.Value);
            foreach (var coin in coinsDescending)
            {
                //Continue to smaller coin when current is larger than remainder
                if (remaining < coin.Value) continue;
                // Get # of coins that fit in remaining amount
                var quotient = (int)(remaining / coin.Value);
    
                Console.WriteLine(new string('-',28));
                Console.WriteLine("{0,10}{1,15}", coin.Name, quotient);
                //Subtract fitting coins from remaining amount
                remaining -= quotient * coin.Value;
                if (remaining <= 0) break; //Exit when no remainder left
            }
            Console.WriteLine(new string('-', 28));
        }
        public class Coin
        {
            public string Name { get; set; }
            public int Value { get; set; }
        }
    }    
    

提交回复
热议问题