Maximum Difference Between Adjacent Elements in a Circular Array - Problem
Maximum Difference Between Adjacent Elements in a Circular Array
You're given a circular array
Think of this array as a circle of numbers where each number has exactly two neighbors - the one before it and the one after it. The special property of a circular array is that the first and last elements are considered adjacent to each other.
Goal: Return the largest absolute difference between any pair of adjacent elements.
Example: For array
You're given a circular array
nums, where the last element connects back to the first element, forming a complete circle. Your task is to find the maximum absolute difference between any two adjacent elements in this circular structure.Think of this array as a circle of numbers where each number has exactly two neighbors - the one before it and the one after it. The special property of a circular array is that the first and last elements are considered adjacent to each other.
Goal: Return the largest absolute difference between any pair of adjacent elements.
Example: For array
[1, 3, 7, 1], the adjacent pairs are: (1,3), (3,7), (7,1), and (1,1). The differences are |1-3|=2, |3-7|=4, |7-1|=6, |1-1|=0. The maximum is 6. Input & Output
example_1.py โ Python
$
Input:
nums = [1, 3, 7, 1]
โบ
Output:
6
๐ก Note:
The adjacent pairs are (1,3), (3,7), (7,1), and (1,1) due to circular nature. Their absolute differences are 2, 4, 6, and 0 respectively. The maximum is 6.
example_2.py โ Python
$
Input:
nums = [5, 5, 5, 5]
โบ
Output:
0
๐ก Note:
All elements are the same, so all adjacent differences are 0. The maximum difference is 0.
example_3.py โ Python
$
Input:
nums = [1, 100]
โบ
Output:
99
๐ก Note:
In a circular array of 2 elements, both pairs (1,100) and (100,1) have the same absolute difference of 99.
Constraints
- 1 โค nums.length โค 103
- -109 โค nums[i] โค 109
- The array is treated as circular - first and last elements are adjacent
Visualization
Tap to expand
Understanding the Visualization
1
Start at Position 0
Begin at the first element and prepare to check all adjacent pairs
2
Check Each Adjacent Pair
For each position i, calculate |nums[i] - nums[(i+1) % n]|
3
Track Maximum
Keep updating the maximum difference as you find larger values
4
Complete the Circle
The last element connects back to the first, completing the circular check
Key Takeaway
๐ฏ Key Insight: In a circular array, every element has exactly two neighbors, and the modulo operator (%) elegantly handles the wraparound from the last element back to the first.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code