3423. Maximum Difference Between Adjacent Elements in a Circular Array LeetCode Solution
In this guide, you will get 3423. Maximum Difference Between Adjacent Elements in a Circular Array LeetCode Solution with the best time and space complexity. The solution to Maximum Difference Between Adjacent Elements in a Circular Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Maximum Difference Between Adjacent Elements in a Circular Array solution in C++
- Maximum Difference Between Adjacent Elements in a Circular Array solution in Java
- Maximum Difference Between Adjacent Elements in a Circular Array solution in Python
- Additional Resources
Problem Statement of Maximum Difference Between Adjacent Elements in a Circular Array
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
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
3423. Maximum Difference Between Adjacent Elements in a Circular Array LeetCode Solution in C++
class Solution {
public:
int maxAdjacentDistance(vector<int>& nums) {
int ans = abs(nums.front() - nums.back());
for (int i = 0; i + 1 < nums.size(); ++i)
ans = max(ans, abs(nums[i] - nums[i + 1]));
return ans;
}
};
/* code provided by PROGIEZ */
3423. Maximum Difference Between Adjacent Elements in a Circular Array LeetCode Solution in Java
class Solution {
public int maxAdjacentDistance(int[] nums) {
int ans = Math.abs(nums[0] - nums[nums.length - 1]);
for (int i = 0; i + 1 < nums.length; ++i)
ans = Math.max(ans, Math.abs(nums[i] - nums[i + 1]));
return ans;
}
}
// code provided by PROGIEZ
3423. Maximum Difference Between Adjacent Elements in a Circular Array LeetCode Solution in Python
class Solution:
def maxAdjacentDistance(self, nums: list[int]) -> int:
return max(abs(nums[i] - nums[i - 1])
for i in range(len(nums)))
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.