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

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

    You can very quickly find an upper bound.

    Say, you take three quarters. Then you would only have to fill in the 'gaps' 1-24, 26-49, 51-74, 76-99 with other coins.

    Trivially, that would work with 2 dimes, 1 nickel, and 4 pennies.

    So, 3 + 4 + 2 + 1 should be an upper bound for your number of coins, Whenever your brute-force algorithm goes above thta, you can instantly stop searching any deeper.

    The rest of the search should perform fast enough for any purpose with dynamic programming.

    (edit: fixed answer as per Gabe's observation)

提交回复
热议问题