File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ public class Main {
6+ static int N , M ;
7+ static int [] arr;
8+
9+ public static void main (String [] args ) throws IOException {
10+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
11+ StringTokenizer st = new StringTokenizer (br. readLine());
12+
13+ N = Integer . parseInt(st. nextToken());
14+ M = Integer . parseInt(st. nextToken());
15+
16+ arr = new int [N ];
17+ st = new StringTokenizer (br. readLine());
18+
19+ int maxVal = 0 ;
20+ int minVal = Integer . MAX_VALUE ;
21+
22+ for (int i = 0 ; i < N ; i++ ) {
23+ arr[i] = Integer . parseInt(st. nextToken());
24+ maxVal = Math . max(maxVal, arr[i]);
25+ minVal = Math . min(minVal, arr[i]);
26+ }
27+
28+ int left = 0 ;
29+ int right = maxVal - minVal;
30+ int answer = right;
31+
32+ while (left <= right) {
33+ int mid = (left + right) / 2 ;
34+
35+ if (canDivide(mid)) {
36+ answer = mid;
37+ right = mid - 1 ;
38+ } else {
39+ left = mid + 1 ;
40+ }
41+ }
42+
43+ System . out. println(answer);
44+ }
45+
46+ static boolean canDivide (int maxScore ) {
47+ int sections = 1 ;
48+ int minInSection = arr[0 ];
49+ int maxInSection = arr[0 ];
50+
51+ for (int i = 1 ; i < N ; i++ ) {
52+ int newMin = Math . min(minInSection, arr[i]);
53+ int newMax = Math . max(maxInSection, arr[i]);
54+
55+ if (newMax - newMin > maxScore) {
56+ sections++ ;
57+ minInSection = arr[i];
58+ maxInSection = arr[i];
59+ } else {
60+ minInSection = newMin;
61+ maxInSection = newMax;
62+ }
63+ }
64+
65+ return sections <= M ;
66+ }
67+ }
68+ ```
You can’t perform that action at this time.
0 commit comments