Leetcode 2210: Count Hills and Valleys in an Array

grid47
grid47
Exploring patterns and algorithms
Mar 31, 2024 5 min read

You are given an integer array ’nums’. A number at index ‘i’ is part of a hill if its closest non-equal neighbors on both sides are smaller than the number at index ‘i’. Similarly, an index ‘i’ is part of a valley if its closest non-equal neighbors on both sides are larger than the number at index ‘i’. Adjacent indices ‘i’ and ‘j’ are part of the same hill or valley if the values at nums[i] and nums[j] are the same. An index must have non-equal neighbors on both sides to be part of a hill or valley. Your task is to count the total number of hills and valleys.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of integers.
Example: nums = [3, 5, 1, 4, 2]
Constraints:
• 3 <= nums.length <= 100
• 1 <= nums[i] <= 100
Output: Return the total number of hills and valleys in the array.
Example: Output: 2
Constraints:
Goal: Identify hills and valleys based on the given conditions.
Steps:
• Iterate through the array and check for each element if it satisfies the hill or valley condition.
• For each element, compare it with the closest non-equal neighbors to determine if it forms a hill or valley.
• Count the number of hills and valleys.
Goal: The array length is between 3 and 100, and each element is between 1 and 100.
Steps:
• 3 <= nums.length <= 100
• 1 <= nums[i] <= 100
Assumptions:
• The input array has at least three elements.
Input: nums = [3, 5, 1, 4, 2]
Explanation: In this example, index 1 is a hill (5 > 3 and 5 > 1), index 2 is a valley (1 < 5 and 1 < 4), and index 3 is a hill (4 > 1 and 4 > 2). Therefore, the total count of hills and valleys is 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus