Skip to content

3423. Maximum Difference Between Adjacent Elements in a Circular Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  int maxAdjacentDistance(vector<int>& nums) {
    int ans = abs(nums.front() - nums.back());

    for (int i = 0; i + 1 < nums.size(); ++i)
      ans = max(ans, abs(nums[i] - nums[i + 1]));

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public int maxAdjacentDistance(int[] nums) {
    int ans = Math.abs(nums[0] - nums[nums.length - 1]);

    for (int i = 0; i + 1 < nums.length; ++i)
      ans = Math.max(ans, Math.abs(nums[i] - nums[i + 1]));

    return ans;
  }
}
1
2
3
4
class Solution:
  def maxAdjacentDistance(self, nums: list[int]) -> int:
    return max(abs(nums[i] - nums[i - 1])
               for i in range(len(nums)))