-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathMinMaxDivision.java
More file actions
46 lines (43 loc) · 834 Bytes
/
MinMaxDivision.java
File metadata and controls
46 lines (43 loc) · 834 Bytes
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
38
39
40
41
42
43
44
45
46
public class MinMaxDivision {
public int solution(int K, int M, int[] A) {
int result = -1;
int lower = max(A);
int upper = sum(A);
while (lower <= upper) {
int middle = (lower + upper) / 2;
if (countBlocks(A, middle) <= K) {
result = middle;
upper = middle - 1;
} else {
lower = middle + 1;
}
}
return result;
}
int max(int[] A) {
int result = Integer.MIN_VALUE;
for (int number : A) {
result = Math.max(result, number);
}
return result;
}
int sum(int[] A) {
int result = 0;
for (int number : A) {
result += number;
}
return result;
}
int countBlocks(int[] A, int largeSum) {
int blockNum = 1;
int remain = largeSum;
for (int number : A) {
if (remain < number) {
remain = largeSum;
blockNum++;
}
remain -= number;
}
return blockNum;
}
}