Skip to content

Commit

Permalink
164th Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Shyam-Chen committed Jul 14, 2024
1 parent cf85632 commit ef40d69
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { countHillValley } from './countHillValley';

describe('2210. Count Hills and Valleys in an Array', () => {
test('countHillValley', () => {
expect(countHillValley([2, 4, 1, 1, 6, 5])).toBe(3);
expect(countHillValley([6, 6, 5, 5, 4, 1])).toBe(0);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
type CountHillValley = (nums: number[]) => number;

/**
* Accepted
*/
export const countHillValley: CountHillValley = (nums) => {
let count = 0;

const n = nums.length;

for (let i = 1; i < n - 1; i++) {
// Skip if current element is the same as the previous one
if (nums[i] === nums[i - 1]) continue;

let left = i - 1;
let right = i + 1;

// Find the closest non-equal neighbor on the left
while (left >= 0 && nums[left] === nums[i]) {
left -= 1;
}

// Find the closest non-equal neighbor on the right
while (right < n && nums[right] === nums[i]) {
right += 1;
}

// Ensure that both left and right neighbors exist
if (left >= 0 && right < n) {
if (nums[i] > nums[left] && nums[i] > nums[right]) {
count += 1; // It's a hill
} else if (nums[i] < nums[left] && nums[i] < nums[right]) {
count += 1; // It's a valley
}
}
}

return count;
};

0 comments on commit ef40d69

Please sign in to comment.