[算法]硬币最小数量

硬币最小数量

问题地址

题目描述

Description

Given the list of coins of distinct denominations and total amount of money. Output the minimum number of coins required to make up that amount. Output -1 if that money cannot be made up using given coins. You may assume that there are infinite numbers of coins of each type.

Input

The first line contains ‘T’ denoting the number of test cases. Then follows description of test cases. Each cases begins with the two space separated integers ‘n’ and ‘amount’ denoting the total number of distinct coins and total amount of money respectively. The second line contains N space-separated integers A1, A2, …, AN denoting the values of coins.

Constraints:1<=T<=30,1<=n<=100,1<=Ai<=1000,1<=amount<=100000

Output

Print the minimum number of coins required to make up that amount or return -1 if it is impossible to make that amount using given coins.

Sample Input 1

2
3 11
1 2 5
2 7
2 6

Sample Output 1

3
-1
题目解析

给你一个目标钱数,和硬币的一个面值列表,问你能不能用最少的硬币去刚刚好凑成目标钱数

本题硬币是无限枚的

eg 凑成11元, 有1 2 5三种类型的硬币,一种一个就正好凑够了,答案为3

思路解析

每次尽可能选择最大的面值,直到该面值不能选取后,再去选下一个面值,重复直到选完或者不能选了为止

但这种方法虽然能通过,但是解这道题有一个问题,请看这个用例
2 8
2 5
即:有8块钱, 有2元和5元的硬币,按照贪心逻辑会无法刚刚选够,因此会输出-1
硬币问题能否使用贪心方法去解取决于硬币的面值组成

这道题期末考了,没过...
代码实现

python

if __name__ == '__main__':
    for i in range(int(input())):
        num, total = list(map(int, input().split(" ")))
        coin_arr = list(set(map(int, input().split(" "))))
        coin_arr.sort(reverse=True)
        count = 0
        i = 0
        while i < len(coin_arr):
            if total - coin_arr[i] >= 0:
                total = total - coin_arr[i]
                count += 1
                if total == 0:
                    break
            else:
                i += 1
        if total == 0:
            print(count)
        else:
            print(-1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值