그리디 알고리즘으로 풀어봤다.
동전은 화폐의 단위가 어떻게 되는지 알 수 없어서
1. n과 total을 일단 Scanner로 받아주고
2. 다음에 들어오는 단위들을 ArrayList에 넣어주면서
3. 가장 큰 단위인 List의 n - 1번째부터 반복문으로 빼주면서 0원이 될 때까지 count++을 해주면서 출력했다.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int total = in.nextInt();
int count = 0;
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(in.nextInt());
}
while (total > 0) {
if (total >= list.get(n-1)) {
total -= list.get(n-1);
count++;
} else {
n--;
}
if (total == 0) break;
}
System.out.println(count);
}
}
근데 Scanner와 System.out.println 을 바꿔서 bufferReader, StringBuilder로 풀어볼까한다. -> 효율이 더 좋다고 해서 연습이 필요하다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String n = br.readLine();
String[] parts = n.split(" ");
int N = Integer.parseInt(parts[0]);
int total = Integer.parseInt(parts[1]);
int count = 0;
List<Integer> list = new ArrayList<>(N);
for (int i = 0; i < N; i++) {
list.add(Integer.valueOf(br.readLine()));
}
StringBuilder sb = new StringBuilder();
while (total > 0) {
if (total >= list.get(N-1)) {
total -= list.get(N-1);
count++;
} else {
N--;
}
if (total == 0) break;
}
sb.append(count);
System.out.println(sb);
}
}