2210. Count Hills and Valleys in an Array #1976
-
Topics: You are given a 0-indexed integer array Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of hills and valleys in an array. A hill is an index where the closest non-equal neighbors on both sides are smaller than the current element. Similarly, a valley is an index where the closest non-equal neighbors on both sides are larger than the current element. Adjacent indices with the same value are considered part of the same hill or valley. Approach
Let's implement this solution in PHP: 2210. Count Hills and Valleys in an Array <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function countHillValley($nums) {
$arr = [];
$n = count($nums);
$arr[] = $nums[0];
for ($i = 1; $i < $n; $i++) {
if ($nums[$i] != $nums[$i - 1]) {
$arr[] = $nums[$i];
}
}
$m = count($arr);
if ($m < 3) {
return 0;
}
$count = 0;
for ($i = 1; $i < $m - 1; $i++) {
if (($arr[$i] > $arr[$i - 1] && $arr[$i] > $arr[$i + 1]) ||
($arr[$i] < $arr[$i - 1] && $arr[$i] < $arr[$i + 1])) {
$count++;
}
}
return $count;
}
// Test cases
echo countHillValley([2,4,1,1,6,5]); // Output: 3
echo countHillValley([6,6,5,5,4,1]); // Output: 0
?> Explanation:
This approach efficiently counts hills and valleys by first simplifying the array to avoid redundant checks on consecutive duplicates, then systematically evaluating each relevant element's neighbors. The solution handles all edge cases and processes the array in linear time. |
Beta Was this translation helpful? Give feedback.
We need to count the number of hills and valleys in an array. A hill is an index where the closest non-equal neighbors on both sides are smaller than the current element. Similarly, a valley is an index where the closest non-equal neighbors on both sides are larger than the current element. Adjacent indices with the same value are considered part of the same hill or valley.
Approach