[LeetCode 3423] Maximum Difference Between Adjacent Elements in a Circular Array
LeetCode 3423 (Java)
[Maximum Difference Between Adjacent Elements in a Circular Array] 문제 풀이
[LeetCode 3423] Maximum Difference Between Adjacent Elements in a Circular Array
Description
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
numsis circular,nums[0]andnums[2]are adjacent. They have the maximum absolute difference of|4 - 1| = 3.
- Because
Example 2
- Input: nums = [-5,-10,-5]
- Output: 5
- Explanation:
- The adjacent elements
nums[0]andnums[1]have the maximum absolute difference of|-5 - (-10)| = 5.
- The adjacent elements
Constraints
2 <= nums.length <= 100-100 <= nums[i] <= 100
Hint
Hint 1
Traverse from the second element to the last element and check the difference of every adjacent pair.
Hint 2
The edge case is to check the difference between the first and last elements.
Code
내 제출
1
2
3
4
5
6
7
8
9
10
11
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;
}
}
| Runtime | Memory |
|---|---|
| 1 ms | 43.3 MB |
다른 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int maxAdjacentDistance(int[] nums) {
int ans=Integer.MIN_VALUE;
List<Integer> l=new ArrayList<>();
for(int i=1;i<nums.length;i++)
{
l.add(Math.abs(nums[i]-nums[i-1]));
}
l.add(Math.abs(nums[0]-nums[nums.length-1]));
for(int i:l)
{
if(i>ans)
ans=i;
}
return ans;
}
}
Reference
- https://github.com/doocs/leetcode/blob/main/solution/3400-3499/3423.Maximum%20Difference%20Between%20Adjacent%20Elements%20in%20a%20Circular%20Array/Solution.java
This post is licensed under CC BY 4.0 by the author.
