Created
June 12, 2025 17:14
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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