-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
minimize-the-maximum-adjacent-element-difference.cpp
58 lines (54 loc) · 1.88 KB
/
minimize-the-maximum-adjacent-element-difference.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
// Time: O(nlogr)
// Space: O(1)
// binary search
class Solution {
public:
int minDifference(vector<int>& nums) {
const auto& binary_search = [](auto left, auto right, const auto& check) {
while (left <= right) {
const auto& mid = left + (right - left) / 2;
if (check(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
};
int max_diff = 0, left = numeric_limits<int>::max(), right = 0;
for (int i = 0; i < size(nums); ++i) {
if (nums[i] != -1) {
if (i + 1 < size(nums) && nums[i + 1] != -1) {
max_diff = max(max_diff, abs(nums[i] - nums[i + 1]));
}
continue;
}
if (i - 1 < size(nums) && nums[i - 1] != -1) {
left = min(left, nums[i - 1]);
right = max(right, nums[i - 1]);
}
if (i + 1 < size(nums) && nums[i + 1] != -1) {
left = min(left, nums[i + 1]);
right = max(right, nums[i + 1]);
}
}
const auto& check = [&](int d) {
for (int i = 0, prev = 0, x = left + d, y = right - d, cnt = 0; i < size(nums); ++i) {
if (nums[i] == -1) {
++cnt;
continue;
}
if (prev && cnt) {
const auto& diff = min(max(abs(prev - x), abs(nums[i] - x)), max(abs(prev - y), abs(nums[i] - y)));
if (diff > d && (cnt == 1 || y - x > d)) {
return false;
}
}
prev = nums[i];
cnt = 0;
}
return true;
};
return binary_search(max_diff, (right - left) / 2, check);
}
};