Maximum Difference Between Adjacent Elements in a Circular Array
Source: leetcode
Difficulty: Easy
Tags: array

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`




C++ solution:
class Solution {
public:
    int maxAdjacentDistance(vector<int>& nums) {
        int n = nums.size();
        int max_diff = 0;
        for (int i = 0; i < n; ++i) {
            int next = (i + 1) % n;
            int diff = abs(nums[i] - nums[next]);
            if (diff > max_diff) {
                max_diff = diff;
            }
        }
        return max_diff;
    }
};

Go solution:
func maxAdjacentDistance(nums []int) int {
    max := 0
    n := len(nums)
    for i := 0; i < n; i++ {
        next := (i + 1) % n
        diff := nums[i] - nums[next]
        if diff < 0 {
            diff = -diff
        }
        if diff > max {
            max = diff
        }
    }
    return max
}

Java solution:
class Solution {
    public int maxAdjacentDistance(int[] nums) {
        int max = 0;
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            int next = (i + 1) % n;
            int diff = Math.abs(nums[i] - nums[next]);
            if (diff > max) {
                max = diff;
            }
        }
        return max;
    }
}

JavaScript solution:
var maxAdjacentDistance = function(nums) {
    let max = 0;
    const n = nums.length;
    for (let i = 0; i < n; i++) {
        const next = (i + 1) % n;
        const diff = Math.abs(nums[i] - nums[next]);
        if (diff > max) max = diff;
    }
    return max;
};

Python solution:
class Solution:
    def maxAdjacentDistance(self, nums: List[int]) -> int:
        max_diff = 0
        n = len(nums)
        for i in range(n):
            next_i = (i + 1) % n
            current_diff = abs(nums[i] - nums[next_i])
            if current_diff > max_diff:
                max_diff = current_diff
        return max_diff

Ruby solution:
def max_adjacent_distance(nums)
    max = 0
    n = nums.size
    (0...n).each do |i|
        next_i = (i + 1) % n
        diff = (nums[i] - nums[next_i]).abs
        max = diff if diff > max
    end
    max
end