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

后端 未结 27 2005
生来不讨喜
生来不讨喜 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:14

    Here's a simple version in Python.

    #!/usr/bin/env python
    
    required = []
    coins = [25, 10, 5, 1]
    
    t = []
    for i in range(1, 100):
        while sum(t) != i:
            for c in coins:
                if sum(t) + c <= i:
                    t.append(c)
                    break
        for c in coins:
            while t.count(c) > required.count(c):
                required.append(c)
        del t[:]
    
    print required
    

    When run, it prints the following to stdout.

    [1, 1, 1, 1, 5, 10, 10, 25, 25, 25]
    

    The code is pretty self-explanatory (thanks Python!), but basically the algorithm is to add the largest coin available that doesn't put you over the current total you're shooting for into your temporary list of coins (t in this case). Once you find the most efficient set of coins for a particular total, make sure there are at least that many of each coin in the required list. Do that for every total from 1 to 99 cents, and you're done.

提交回复
热议问题