Brush Question 41-Collecting Change Problem (Greedy Algorithm)

Original title link

Extended topic one ------ minimum loading quantity (unlimited quantity of each type of goods)

Title description

楚乔、宇文玥和燕洵在日本旅行,经过了几天的游玩之后,钱包里出现了大量硬币,楚乔决定用钱包里的硬币为宇文玥和燕洵在自动贩卖机买水。
楚乔的钱包里有1元、5元、10元、50元、100元和500元硬币,
各C1,C5,C10,C50,C100,C500枚。
现在要用这些硬币来到自动贩卖机买价格为A的饮料,
假设自动贩卖机所需的硬币金额必须是刚刚好,不能多也不能少,最少需要多少枚硬币?

限制条件:
0≤ C1,C5,C10,C50,C100,C500≤1000000000
0≤A≤1000000000
依次输入C1,C5,C10,C50,C100,C500和A,以空格分隔,输出最少所需硬币数,如果该金额不能由所给硬币凑出,则返回NOWAY

Example

输入:
3 2 1 3 0 2 620
输出:
6

Reference solution

硬币面值属于倍数关系,使用贪心算法可以求得最优解

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner in = new Scanner(System.in);
        int[] money = {
    
    1, 5, 10, 50, 100, 500};
        int[] count = new int[6];
        for (int i = 0; i < 6; i++) {
    
    
            count[i] = in.nextInt();
        }
        int A = in.nextInt();
        int ans = 0;
        // 硬币面值属于倍数关系,可以使用贪心算法
        for (int i = 5; i >= 0; i--) {
    
    
            int temp = A / money[i];
            if (temp <= count[i]) {
    
    
                ans += temp;
                A -= temp * money[i];
            } else {
    
    
                ans += count[i];
                A -= count[i] * money[i];
            }
        }
        // 满足条件
        if(A==0)
            System.out.println(ans);
        else
            System.out.println("NOWAY");
    }
}

Guess you like

Origin blog.csdn.net/Awt_FuDongLai/article/details/111239405