comments | difficulty | edit_url |
---|---|---|
true |
Easy |
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
We traverse the array
The time complexity is
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]))
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;
}
}
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;
}
};
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
}
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;
}