Skip to main content

Command Palette

Search for a command to run...

Count Hills and Valleys in an Array

Published
2 min read
Count Hills and Valleys in an Array
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

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].

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 nums.

LeetCode Problem - 2210

class Solution {
    public int countHillValley(int[] nums) {
        // Initialize a counter to keep track of the number of hills and valleys
        int answer = 0;

        // Iterate through the array, starting from the second element and ending at the second-to-last element
        for(int i = 1; i < nums.length - 1; i++) {
            // Check if the current element is a hill (greater than both its neighbors)
            if(nums[i] > nums[i + 1] && nums[i] > nums[i - 1]) {
                answer++; // Increment the count for a hill
            }
            // Check if the current element is a valley (less than both its neighbors)
            if(nums[i] < nums[i + 1] && nums[i] < nums[i - 1]) {
                answer++; // Increment the count for a valley
            }
            // If the current element is equal to the next element, make it equal to the previous element
            // This is done to avoid counting the same peak or valley multiple times due to plateaus
            if(nums[i] == nums[i + 1]) {
                nums[i] = nums[i - 1];
            }
        }

        // Return the total count of hills and valleys
        return answer;
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.