[BaekJoon] #1475 - 방 번호 [Java][C++]
[BaekJoon] #1475 - 방 번호 [Java][C++]
1. 아이디어
플라스틱 한 세트는 0번부터 9번까지의 숫자가 하나씩 들어있으며 6번은 9번으로, 9번은 6번으로 활용할 수 있다. 따라서 방 번호가 주어졌을 때 필요한 세트의 개수는 0번부터 9번까지 중 6번과 9번을 제외한 나머지 숫자들에 대해 각 숫자의 개수의 최댓값만큼은 일단 필요하다. 그리고 6번과 9번은 서로 호환이 가능하므로 6번과 9번의 평균 개수만큼은 필요하다. 이때 6번과 9번의 개수의 합이 홀수 개인 경우 세트는 자연수 개가 있어야 하므로 올림 나눗셈을 해서 최소 개수를 구해야 한다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = s의 길이)
3. 코드
풀이 [Java][C++]
방 번호를 문자열로 받고 카운팅 배열을 활용해서 각 번호의 개수를 셌다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] cnt = new int[10];
String s = br.readLine();
for (char c : s.toCharArray()) {
cnt[c - '0']++;
}
int max = 0;
for (int i = 0; i < 10; i++) {
if (i == 6 || i == 9) continue;
max = Math.max(max, cnt[i]);
}
max = Math.max(max, (cnt[6] + cnt[9] + 1) / 2);
System.out.println(max);
}
}
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
#include <bits/stdc++.h>
using namespace std;
int cnt[10];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
string s;
cin >> s;
for (char c : s) {
cnt[c - '0']++;
}
int mx = 0;
for (int i = 0; i < 10; i++) {
if (i == 6 || i == 9) continue;
mx = max(mx, cnt[i]);
}
mx = max(mx, (cnt[6] + cnt[9] + 1) / 2);
cout << mx;
}
This post is licensed under CC BY 4.0 by the author.