Table of contents
Algorithm running results and calculation time complexity analysis
Problem Description:
There are several coins of 1 cent, 2 cents, 5 cents, 10 cents, 50 cents, and 100 cents. Now you want to use these coins to pay W yuan. Please design a greedy algorithm to complete it with as few coins as possible . payment behavior. There are several coins of 1 cent, 2 cents, 5 cents, 10 cents, 50 cents, and 100 cents. Now you want to use these coins to pay W yuan. Please design a greedy algorithm to complete it with as few coins as possible . payment behavior.
Algorithm Design Ideas:
Design a for loop to perform operations, and the number of loops is actually linked to the number of sheets. Set the condition, if ww>arr[i] (the largest denomination currently accepted), i-- will not be executed, maybe the denomination can be reduced once. If it cannot be reduced, execute i--, let the next smaller denomination try, and so on. Finally, if ww=0, the result can be output.
Code:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
double w = sc.nextDouble();
int ww = (int)(w*100);//把元单位转换为分
int arr[] = new int[6];
for (int i = 0; i < 6; i++) {//输入硬币的几种面额
int a = sc.nextInt();
arr[i] = a;
}
// Arrays.sort(arr);//若是乱序,则需要排序
int num = 0;//存储使用张数
for (int i = 5; i >= 0;) {//因为排序默认从小到大,所以这里要从后往前
if (ww >= arr[i]) {
ww = ww - arr[i];
// i++;
num++;//每使用一张,加1
} else {
i--;//把i--安排在这里,上面只要最大的面额还能用,就不减;不能用了,就执行i--
}
if (ww == 0) {
System.out.println(num);//输出张数
break;
}
}
}
}
}
Algorithm running results and calculation time complexity analysis:
If sorting is required, the time complexity is T(n)=O(nlogn)
If no sorting is required, the time complexity is T(n)=O(n)