Skip to content

Commit 3565cb0

Browse files
committed
3357. Minimize the Maximum Adjacent Element Difference
1 parent f3b1dd1 commit 3565cb0

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// Solution by Sergey Leschev
2+
// 3357. Minimize the Maximum Adjacent Element Difference
3+
// Binary Search
4+
5+
function checkDifference(nums: number[], x: number, y: number, d: number): boolean {
6+
let prev = 0
7+
let count = 0
8+
9+
for (let i = 0; i < nums.length; ++i) {
10+
if (nums[i] === -1) {
11+
if (prev && Math.min(Math.abs(prev - x), Math.abs(prev - y)) > d) {
12+
return false
13+
}
14+
count++
15+
} else {
16+
if (count) {
17+
const diff = prev
18+
? Math.min(Math.max(Math.abs(prev - x), Math.abs(nums[i] - x)), Math.max(Math.abs(prev - y), Math.abs(nums[i] - y)))
19+
: Math.min(Math.abs(nums[i] - x), Math.abs(nums[i] - y))
20+
21+
if (diff > d && (count === 1 || y - x > d)) {
22+
return false
23+
}
24+
}
25+
prev = nums[i]
26+
count = 0
27+
}
28+
}
29+
return true
30+
}
31+
32+
function minDifference(nums: number[]): number {
33+
let maxGap = 0
34+
let minVal = Number.MAX_SAFE_INTEGER
35+
let maxVal = 0
36+
37+
for (let i = 0; i + 1 < nums.length; ++i) {
38+
if (Math.min(nums[i], nums[i + 1]) === -1 && Math.max(nums[i], nums[i + 1]) !== -1) {
39+
minVal = Math.min(minVal, Math.max(nums[i], nums[i + 1]))
40+
maxVal = Math.max(maxVal, Math.max(nums[i], nums[i + 1]))
41+
} else if (nums[i] !== -1 && nums[i + 1] !== -1) {
42+
maxGap = Math.max(maxGap, Math.abs(nums[i] - nums[i + 1]))
43+
}
44+
}
45+
46+
let left = maxGap
47+
let right = Math.ceil((maxVal - minVal + 1) / 2)
48+
49+
while (left < right) {
50+
const d = Math.floor((left + right) / 2)
51+
if (checkDifference(nums, minVal + d, maxVal - d, d)) {
52+
right = d
53+
} else {
54+
left = d + 1
55+
}
56+
}
57+
58+
return left
59+
}

0 commit comments

Comments
 (0)