Hey problem solvers! π―
Today weβre tackling a fun and elegant problem from LeetCode β 3423: Maximum Difference Between Adjacent Elements in a Circular Array. This one checks your understanding of array boundaries and circular behavior. Letβs break it down. π
π Problem Overview
You're given a circular array nums
, and your task is to find the maximum absolute difference between adjacent elements, where:
- The first and last elements are also considered adjacent (because it's circular).
- You return the maximum absolute difference between any two adjacent numbers.
β¨ Example
Input: nums = [1, 2, 4]
Output: 3
Explanation:
Adjacent pairs: |1 - 2| = 1
, |2 - 4| = 2
, |4 - 1| = 3
.
Max is 3
.
π§ Intuition
The array is circular, so both regular adjacent pairs and the pair between the last and first element must be considered.
Strategy:
- Initialize
ans
with|nums[0] - nums[n-1]|
. - Iterate through the array and compute
|nums[i] - nums[i+1]|
for all validi
. - Return the maximum of all these values.
βοΈ C++ Code
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;
}
};
π JavaScript Version
var maxAdjacentDistance = function(nums) {
let ans = Math.abs(nums[0] - nums[nums.length - 1]);
for (let i = 0; i + 1 < nums.length; ++i) {
ans = Math.max(ans, Math.abs(nums[i] - nums[i + 1]));
}
return ans;
};
π Python Version
def maxAdjacentDistance(nums):
ans = abs(nums[0] - nums[-1])
for i in range(len(nums) - 1):
ans = max(ans, abs(nums[i] - nums[i + 1]))
return ans
π§ͺ Test Cases
Input: nums = [1, 2, 4]
Output: 3
Input: nums = [-5, -10, -5]
Output: 5
Input: nums = [0, 100, -100]
Output: 200
β± Time & Space Complexity
Time Complexity: O(n) β one pass through the array
Space Complexity: O(1) β constant extra space
β Wrap-Up
This is a great warm-up problem to train your attention to edge conditions like circular connections. Simple logic and clean implementation go a long way here.
If this guide helped you, drop a β€οΈ and follow for more beginner-friendly coding guides!
Happy coding! π
Top comments (3)
Well Explained
Thanks Anna!!
Some comments may only be visible to logged-in visitors. Sign in to view all comments.