Java - [백준] 11047 - 동전 0

제훈·2024년 7월 17일

코딩테스트

목록 보기
2/2

그리디 알고리즘으로 풀어봤다.

동전은 화폐의 단위가 어떻게 되는지 알 수 없어서
1. ntotal을 일단 Scanner로 받아주고
2. 다음에 들어오는 단위들을 ArrayList에 넣어주면서
3. 가장 큰 단위인 Listn - 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);
    }
}

근데 ScannerSystem.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);
    }
}
profile
백엔드 개발자 꿈나무

0개의 댓글