[Leetcode] 2210. Count Hills and Valleys in an Array

whitehousechef·2025년 7월 28일

https://leetcode.com/problems/count-hills-and-valleys-in-an-array/

initial

i tried thinking fo using 2 pointers to mark nearby neighbours but actually theres a much eaiser trick. When we see the same number, we update the current number with the previous number instead. So if it is like 4,1,1,6 and we are at the first 1, we update that 1 with 4 so that it becomes 4,4,1,6. Then the second 1 will be correctly marked as valley. This is clever trick

sol

class Solution:
    def countHillValley(self, nums: List[int]) -> int:
        hillValley = 0
        for i in range(1, len(nums)-1):
            if nums[i] == nums[i+1]:
                nums[i] = nums[i-1]
            if nums[i] > nums[i-1] and nums[i] > nums[i+1]:     #hill check
                hillValley += 1
            if nums[i] < nums[i-1] and nums[i] < nums[i+1]:     #valley check
                hillValley += 1
        return hillValley
        

complexity

n time
1 space

0개의 댓글