Skip to content

Commit a8cd460

Browse files
authored
[20251112] BOJ / G4 / 좋다 / 구간 나누기 2
1 parent 046fe46 commit a8cd460

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
```
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
private static int[] arr;
9+
private static int N, M, max, min;
10+
public static void main(String[] args) throws IOException {
11+
init();
12+
int answer = binarySearch();
13+
14+
bw.write(answer + "\n");
15+
bw.flush();
16+
bw.close();
17+
br.close();
18+
}
19+
20+
private static void init() throws IOException {
21+
StringTokenizer st = new StringTokenizer(br.readLine());
22+
N = Integer.parseInt(st.nextToken());
23+
M = Integer.parseInt(st.nextToken());
24+
max = 0;
25+
min = 10001;
26+
27+
arr = new int[N];
28+
29+
st = new StringTokenizer(br.readLine());
30+
for (int i = 0; i < N; i++) {
31+
arr[i] = Integer.parseInt(st.nextToken());
32+
max = Math.max(max, arr[i]);
33+
min = Math.min(min, arr[i]);
34+
}
35+
}
36+
37+
private static int binarySearch() {
38+
int left = 0;
39+
int right = max-min;
40+
int result = right;
41+
42+
while (left <= right) {
43+
int mid = left + (right - left)/2;
44+
45+
if (valid(mid)) {
46+
result = mid;
47+
right = mid-1;
48+
} else {
49+
left = mid+1;
50+
}
51+
}
52+
53+
return result;
54+
}
55+
56+
private static boolean valid(int target) {
57+
int index = 0;
58+
int count = 1;
59+
int max = 0;
60+
int min = 10001;
61+
62+
while (index < N) {
63+
max = Math.max(max, arr[index]);
64+
min = Math.min(min, arr[index]);
65+
66+
if (max-min > target) {
67+
count++;
68+
max = 0;
69+
min = 10001;
70+
index--;
71+
}
72+
73+
index++;
74+
}
75+
76+
return count <= M;
77+
}
78+
}
79+
```

0 commit comments

Comments
 (0)