2210. Count Hills and Valleys in an Array Easy
1/**
2 * [2210] Count Hills and Valleys in an Array
3 *
4 * You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j].
5 * 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.
6 * Return the number of hills and valleys in nums.
7 *
8 * Example 1:
9 *
10 * Input: nums = [2,4,1,1,6,5]
11 * Output: 3
12 * Explanation:
13 * At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.
14 * At index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill.
15 * At index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.
16 * At index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.
17 * At index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.
18 * At index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley.
19 * There are 3 hills and valleys so we return 3.
20 *
21 * Example 2:
22 *
23 * Input: nums = [6,6,5,5,4,1]
24 * Output: 0
25 * Explanation:
26 * At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.
27 * At index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.
28 * At index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.
29 * At index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.
30 * At index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.
31 * At index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.
32 * There are 0 hills and valleys so we return 0.
33 *
34 *
35 * Constraints:
36 *
37 * 3 <= nums.length <= 100
38 * 1 <= nums[i] <= 100
39 *
40 */
41pub struct Solution {}
42
43// problem: https://leetcode.com/problems/count-hills-and-valleys-in-an-array/
44// discuss: https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/?currentPage=1&orderBy=most_votes&query=
45
46// submission codes start here
47
48impl Solution {
49 pub fn count_hill_valley(nums: Vec<i32>) -> i32 {
50 0
51 }
52}
53
54// submission codes end
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59
60 #[test]
61 fn test_2210() {
62 }
63}
64
Back
© 2025 bowen.ge All Rights Reserved.