-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path043. MaxMinHeight.java
More file actions
43 lines (42 loc) · 1.21 KB
/
043. MaxMinHeight.java
File metadata and controls
43 lines (42 loc) · 1.21 KB
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
class Solution {
public int maxMinHeight(int[] arr, int k, int w) {
int n = arr.length;
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
for (int a : arr) {
low = Math.min(low, a);
high = Math.max(high, a);
}
high += k;
int result = low;
while (low <= high) {
int mid = low + (high - low) / 2;
if (canReach(arr, k, w, mid)) {
result = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
private boolean canReach(int[] arr, int k, int w, int target) {
int n = arr.length;
int[] diff = new int[n + 2];
long used = 0;
long curr = 0;
for (int i = 0; i < n; i++) {
curr += diff[i];
long height = arr[i] + curr;
if (height < target) {
long need = target - height;
used += need;
if (used > k) return false;
curr += need;
diff[i] += need;
if (i + w < diff.length) diff[i + w] -= need;
}
}
return true;
}
}