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

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

    You need at least 4 pennies, since you want to get 4 as a change, and you can do that only with pennies.

    It isn't optimal to have more than 4 pennies. Instead of 4+x pennies, you can have 4 pennies and x nickels - they span at least the same range.

    So you have exactly 4 pennies.

    You need at least 1 nickel, since you want to get 5 as a change.

    It isn't optimal to have more than 1 nickel. Instead of 1+x nickels, you can have 1 nickel and x dimes - they span at least the same range.

    So you have exactly 1 nickel.

    You need at least 2 dimes, since you want to get 20.

    This means you have 4 pennies, 1 nickel and at least 2 dimes.

    If you had less than 10 coins, you would have less than 3 quarters. But then the maximal possible change you could get using all coins is 4 + 5 + 20 + 50 = 79, not enough.

    This means you have at least 10 coins. Thomas's answer shows that in fact if you have 4 pennies, 1 nickel, 2 dimes and 3 quarters, all is well.

提交回复
热议问题