Input: nums =[1,2,4]Output: 3Explanation:
Because `nums`is circular,`nums[0]` and `nums[2]` are adjacent. They have the maximum absolute difference of `|4 - 1| = 3`.
Input: nums =[-5,-10,-5]Output: 5Explanation:
The adjacent elements `nums[0]` and `nums[1]` have the maximum absolute difference of `|-5 - (-10)| = 5`.
The maximum absolute difference between adjacent elements in a circular array can be found by checking the difference between every pair of consecutive elements, including the pair formed by the last and first elements. This works because the largest jump could be anywhere in the array, including the wrap-around.
classSolution {
public:int maxAdjacentDistance(vector<int>& nums) {
int n = nums.size(), ans =0;
for (int i =0; i < n; ++i) {
int diff = abs(nums[i] - nums[(i +1) % n]);
if (diff > ans) ans = diff;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
funcmaxAdjacentDistance(nums []int) int {
n, ans:= len(nums), 0fori:=0; i < n; i++ {
diff:=nums[i] -nums[(i+1)%n]
ifdiff < 0 {
diff = -diff }
ifdiff > ans {
ans = diff }
}
returnans}
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintmaxAdjacentDistance(int[] nums) {
int n = nums.length, ans = 0;
for (int i = 0; i < n; i++) {
int diff = Math.abs(nums[i]- nums[(i + 1) % n]);
if (diff > ans) ans = diff;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funmaxAdjacentDistance(nums: IntArray): Int {
val n = nums.size
var ans = 0for (i in0 until n) {
val diff = kotlin.math.abs(nums[i] - nums[(i + 1) % n])
if (diff > ans) ans = diff
}
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defmaxAdjacentDistance(self, nums: list[int]) -> int:
n: int = len(nums)
ans: int =0for i in range(n):
diff: int = abs(nums[i] - nums[(i +1) % n])
if diff > ans:
ans = diff
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnmax_adjacent_distance(nums: Vec<i32>) -> i32 {
let n = nums.len();
letmut ans =0;
for i in0..n {
let diff = (nums[i] - nums[(i +1) % n]).abs();
if diff > ans {
ans = diff;
}
}
ans
}
}