Maximum Difference Between Adjacent Elements in a Circular Array - Problem

Given a circular array nums, find the maximum absolute difference between adjacent elements.

Note: In a circular array, the first and last elements are adjacent.

For example, if nums = [1, 5, 3, 9], the adjacent pairs are: (1,5), (5,3), (3,9), and (9,1).

Input & Output

Example 1 — Basic Circular Array
$ Input: nums = [1, 5, 3, 9]
Output: 8
💡 Note: Adjacent pairs are: (1,5)→4, (5,3)→2, (3,9)→6, (9,1)→8. Maximum difference is 8 between last and first elements.
Example 2 — Small Array
$ Input: nums = [2, 7]
Output: 5
💡 Note: Only one adjacent pair: (2,7) and (7,2), both have difference |2-7| = 5.
Example 3 — All Same Elements
$ Input: nums = [5, 5, 5, 5]
Output: 0
💡 Note: All adjacent differences are |5-5| = 0, so maximum is 0.

Constraints

  • 2 ≤ nums.length ≤ 104
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Maximum Difference Between Adjacent Elements Circular Array Problem INPUT 1 idx 0 5 idx 1 3 idx 2 9 idx 3 nums = [1, 5, 3, 9] Circular: 9 is adjacent to 1 Adjacent pairs: (1,5), (5,3), (3,9), (9,1) Differences: 4, 2, 6, 8 ALGORITHM STEPS 1 Initialize maxDiff = 0 2 Loop through array For i = 0 to n-1 3 Calculate difference |nums[i] - nums[(i+1)%n]| 4 Update maximum maxDiff = max(maxDiff, diff) Iterations: i=0: |1-5| = 4 max=4 i=1: |5-3| = 2 max=4 i=2: |3-9| = 6 max=6 i=3: |9-1| = 8 max=8 (9,1) is circular pair! FINAL RESULT Maximum difference found between: 9 1 circular |9 - 1| = 8 Output: 8 OK - Maximum Found! Time: O(n), Space: O(1) Single pass through array with modulo for circular wrap Key Insight: In a circular array, the last element wraps around to connect with the first element. Using modulo operation (i+1)%n handles this wrap-around elegantly in a single pass. This achieves O(n) time complexity with O(1) space - optimal for this problem! TutorialsPoint - Maximum Difference Between Adjacent Elements in a Circular Array | Single Pass Optimized
Asked in
Google 25 Amazon 20 Microsoft 15
26.4K Views
Medium Frequency
~8 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen