Maximum Difference Between Adjacent Elements in a Circular Array
EasyUpdated: Aug 2, 2025
Practice on:
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.
Examples
Example 1
Input: nums = [1,2,4]
Output: 3
Explanation:
Because `nums` is circular, `nums[0]` and `nums[2]` are adjacent. They have the maximum absolute difference of `|4 - 1| = 3`.
Example 2
Input: nums = [-5,-10,-5]
Output: 5
Explanation:
The adjacent elements `nums[0]` and `nums[1]` have the maximum absolute difference of `|-5 - (-10)| = 5`.
Constraints
2 <= nums.length <= 100-100 <= nums[i] <= 100
Solution
Method 1 – Single Pass with Circular Check
Intuition
The maximum absolute difference between adjacent elements in a circular array can be found by checking the difference between every pair of consecutive elements, including the pair formed by the last and first elements. This works because the largest jump could be anywhere in the array, including the wrap-around.
Approach
- Initialize a variable
ansto store the maximum absolute difference. - Iterate through the array:
- For each index
i, compute the absolute difference betweennums[i]andnums[(i+1) % n](wherenis the length of the array). - Update
ansif the current difference is greater.
- Return
ansafter the loop.
Code
C++
class Solution {
public:
int maxAdjacentDistance(vector<int>& nums) {
int n = nums.size(), ans = 0;
for (int i = 0; i < n; ++i) {
int diff = abs(nums[i] - nums[(i + 1) % n]);
if (diff > ans) ans = diff;
}
return ans;
}
};
Go
func maxAdjacentDistance(nums []int) int {
n, ans := len(nums), 0
for i := 0; i < n; i++ {
diff := nums[i] - nums[(i+1)%n]
if diff < 0 {
diff = -diff
}
if diff > ans {
ans = diff
}
}
return ans
}
Java
class Solution {
public int maxAdjacentDistance(int[] nums) {
int n = nums.length, ans = 0;
for (int i = 0; i < n; i++) {
int diff = Math.abs(nums[i] - nums[(i + 1) % n]);
if (diff > ans) ans = diff;
}
return ans;
}
}
Kotlin
class Solution {
fun maxAdjacentDistance(nums: IntArray): Int {
val n = nums.size
var ans = 0
for (i in 0 until n) {
val diff = kotlin.math.abs(nums[i] - nums[(i + 1) % n])
if (diff > ans) ans = diff
}
return ans
}
}
Python
class Solution:
def maxAdjacentDistance(self, nums: list[int]) -> int:
n: int = len(nums)
ans: int = 0
for i in range(n):
diff: int = abs(nums[i] - nums[(i + 1) % n])
if diff > ans:
ans = diff
return ans
Rust
impl Solution {
pub fn max_adjacent_distance(nums: Vec<i32>) -> i32 {
let n = nums.len();
let mut ans = 0;
for i in 0..n {
let diff = (nums[i] - nums[(i + 1) % n]).abs();
if diff > ans {
ans = diff;
}
}
ans
}
}
Complexity
- ⏰ Time complexity:
O(n)— Each element is checked once. - 🧺 Space complexity:
O(1)— Only a few variables are used.