From ef40d69e2330de223c1bf8b53cf3e84abe9f278f Mon Sep 17 00:00:00 2001 From: Shyam-Chen Date: Sun, 14 Jul 2024 16:27:26 +0800 Subject: [PATCH] 164th Commit --- .../countHillValley.test.ts | 8 ++++ .../countHillValley.ts | 39 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/page-20/2210. Count Hills and Valleys in an Array/countHillValley.test.ts create mode 100644 src/page-20/2210. Count Hills and Valleys in an Array/countHillValley.ts diff --git a/src/page-20/2210. Count Hills and Valleys in an Array/countHillValley.test.ts b/src/page-20/2210. Count Hills and Valleys in an Array/countHillValley.test.ts new file mode 100644 index 0000000..1a1546f --- /dev/null +++ b/src/page-20/2210. Count Hills and Valleys in an Array/countHillValley.test.ts @@ -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); + }); +}); diff --git a/src/page-20/2210. Count Hills and Valleys in an Array/countHillValley.ts b/src/page-20/2210. Count Hills and Valleys in an Array/countHillValley.ts new file mode 100644 index 0000000..c45c658 --- /dev/null +++ b/src/page-20/2210. Count Hills and Valleys in an Array/countHillValley.ts @@ -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; +};