有n个人正在饭堂排队买海北鸡饭。每份海北鸡饭要25元。奇怪的是,每个人手里只有一张钞票(每张钞票的面值为25、50、100元),而且饭堂阿姨一开始没有任何零钱。请问饭堂阿姨能否给所有人找零(假设饭堂阿姨足够聪明)
思路:
一个数组存储n个人的费用,另一个集合来存所要找的零钱,考虑顺序
代码:
import java.util.ArrayList; import java.util.Scanner; public class Main{ public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } System.out.println(test(arr, list)); } public static String test(int[] arr, ArrayList<Integer> list) { int keyi=0; for (int i = 0; i < arr.length; i++) { if (arr[i] == 25) { list.add(arr[i]); keyi++; } else if (arr[i] == 50) { for (int j = 0; j < list.size(); j++) { if (list.get(j) == 25) { list.remove(j); list.add(50); keyi++; break; } } } else if (arr[i] == 100) { int twenteFive=0; int fifty=0; for (int j = 0; j<list.size(); j++) { if(list.get(j)==25) { twenteFive++; }else if(list.get(j)==50) { fifty++; } } if(twenteFive>=3 || fifty>=1&&twenteFive>=1) { if(fifty>=1&&twenteFive>=1) { for (int j = 0; j < list.size(); j++) { if(list.get(j)==25) { list.remove(j); break; } } for (int j = 0; j <list.size(); j++) { if(list.get(j)==50) { list.remove(j); break; } } keyi++; } else if(twenteFive>=3) { for (int j = 0; j <3; j++) { for (int j2 = 0; j2 < list.size(); j2++) { if(list.get(j2)==25) { list.remove(j2); break; } } } keyi++; } } } } if (keyi==arr.length){ return "YES"; }else { return "NO"; } } }