Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created June 12, 2025 17:14
Show Gist options
  • Save tatsuyax25/8daf1400388683420773db0cc4cbc9f6 to your computer and use it in GitHub Desktop.
Save tatsuyax25/8daf1400388683420773db0cc4cbc9f6 to your computer and use it in GitHub Desktop.
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.
/**
* @param {number[]} nums
* @return {number}
*/
var maxAdjacentDistance = function(nums) {
if (nums.length < 2) return 0; // If there's only one element, no adjacent pairs exist.
let maxDiff = 0; // Initialize a variable to store the maximum absolute difference
for (let i = 0; i < nums.length; i++) {
// Compute the absolute difference between the current element and the next one.
// Using modulus (%) ensures that the last element wraps around to the first element.
let diff = Math.abs(nums[i] - nums[(i + 1) % nums.length]);
// Update maxDiff if the current difference is greater
maxDiff = Math.max(maxDiff, diff);
}
return maxDiff; // Return the maximum absolute difference found
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment