3423. Maximum Difference Between Adjacent Elements in a Circular Array #1797
-
Topics: Given a circular array Note: In a circular array, the first and last elements are adjacent. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum absolute difference between adjacent elements in a circular array. In a circular array, the first and last elements are considered adjacent. The solution involves checking all adjacent pairs, including the pair formed by the last and first elements. Approach
Let's implement this solution in PHP: 3423. Maximum Difference Between Adjacent Elements in a Circular Array <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maxAdjacentDistance($nums) {
$n = count($nums);
$max_diff = 0;
for ($i = 0; $i < $n; $i++) {
$j = ($i + 1) % $n;
$diff = abs($nums[$i] - $nums[$j]);
if ($diff > $max_diff) {
$max_diff = $diff;
}
}
return $max_diff;
}
// Example 1
$nums1 = [1, 2, 4];
echo "Output: " . maxAdjacentDistance($nums1) . "\n"; // Output: 3
// Example 2
$nums2 = [-5, -10, -5];
echo "Output: " . maxAdjacentDistance($nums2) . "\n"; // Output: 5
?> Explanation:
This approach efficiently checks all adjacent pairs in the circular array, ensuring the solution is both optimal and straightforward. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum absolute difference between adjacent elements in a circular array. In a circular array, the first and last elements are considered adjacent. The solution involves checking all adjacent pairs, including the pair formed by the last and first elements.
Approach