Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A circular array has all the usual adjacent pairs plus one extra pair connecting its last element to its first. Checking those pairs directly is sufficient; nonadjacent elements never need comparison.
Approach
Scan indices from one through the end of the array. For each index, compute the absolute difference between the current value and the previous value, keeping the largest seen. Then compare that maximum with the absolute difference between the first and last elements. Return the final maximum.
The absolute value makes the order of a pair irrelevant, including when values are negative. The separate wraparound comparison is essential because that pair is not visited by the ordinary scan. For a two-element array, examining the same unordered pair again does not change the answer.
class Solution:
def maxAdjacentDistance(self, nums: List[int]) -> int:
res = float('-inf')
for i in range(1, len(nums)):
res = max(res, abs(nums[i] - nums[i - 1]))
res = max(res, abs(nums[0] - nums[-1]))
return resComplexity analysis
Let n = nums.length. Time: O(n). Auxiliary space: O(1).
