Skip to content

3423. Maximum Difference Between Adjacent Elements in a Circular Array

Description

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.

 

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

Solutions

Solution 1: Simulation

We traverse the array $\textit{nums}$, calculate the absolute difference between adjacent elements, and maintain the maximum absolute difference. Finally, we compare it with the absolute difference between the first and last elements and take the maximum value.

The time complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. The space complexity is $O(1)$.

1
2
3
class Solution:
    def maxAdjacentDistance(self, nums: List[int]) -> int:
        return max(max(abs(a - b) for a, b in pairwise(nums)), abs(nums[0] - nums[-1]))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    public int maxAdjacentDistance(int[] nums) {
        int n = nums.length;
        int ans = Math.abs(nums[0] - nums[n - 1]);
        for (int i = 1; i < n; ++i) {
            ans = Math.max(ans, Math.abs(nums[i] - nums[i - 1]));
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
public:
    int maxAdjacentDistance(vector<int>& nums) {
        int ans = abs(nums[0] - nums.back());
        for (int i = 1; i < nums.size(); ++i) {
            ans = max(ans, abs(nums[i] - nums[i - 1]));
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
func maxAdjacentDistance(nums []int) int {
    ans := abs(nums[0] - nums[len(nums)-1])
    for i := 1; i < len(nums); i++ {
        ans = max(ans, abs(nums[i]-nums[i-1]))
    }
    return ans
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}
1
2
3
4
5
6
7
8
function maxAdjacentDistance(nums: number[]): number {
    const n = nums.length;
    let ans = Math.abs(nums[0] - nums[n - 1]);
    for (let i = 1; i < n; ++i) {
        ans = Math.max(ans, Math.abs(nums[i] - nums[i - 1]));
    }
    return ans;
}

Comments