그리디 알고리즘

뒤에서부터 K값보다 그 가치가 크면 계속 반복문 돌고 그렇지 않으면 몫을 계산하여 count에 증가시켜주고 cnt * value[i] 만큼 K에서 빼줍니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package greedy;
 
 
public class Main11047_동전 {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine()," ");
        int N = Integer.parseInt(st.nextToken());
        int K = Integer.parseInt(st.nextToken());
        int[] value = new int[N];
        for (int i = 0; i < N; i++) {
            int Ai = Integer.parseInt(br.readLine());
            value[i] = Ai;
        }
        
        int count = 0;
        for (int i = value.length-1; i >=0; i--) {
            if(value[i] > K) continue;
            else {
                int cnt = K / value[i];;
                count += cnt; 
                K = K - (cnt * value[i]);
            }
            
            if(K ==0) {
                break;
            }
        }
        
        System.out.println(count);
    }//end of main
}//end of class
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none; color:white">cs

+ Recent posts