diff --git a/README.md b/README.md index c547227..53ed720 100644 --- a/README.md +++ b/README.md @@ -83,4 +83,5 @@ - [Task #10](src/neetcode/two-pointers/valid-palindrome) - _Valid Palindrome_ - _[check the task](https://neetcode.io/problems/is-palindrome)_ - [Task #11](src/neetcode/two-pointers/two-sum-ii-input-array-is-sorted) - _Two Sum II Input Array Is Sorted_ - _[check the task](https://neetcode.io/problems/two-integer-sum-ii)_ - [Task #12](src/neetcode/two-pointers/3sum) - _3Sum_ - _[check the task](https://neetcode.io/problems/three-integer-sum)_ - - [Task #13](src/neetcode/two-pointers/container-with-most-water) - _Container With Most Water_ - _[check the task](https://neetcode.io/problems/max-water-container)_ \ No newline at end of file + - [Task #13](src/neetcode/two-pointers/container-with-most-water) - _Container With Most Water_ - _[check the task](https://neetcode.io/problems/max-water-container)_ + - [Task #14](src/neetcode/two-pointers/trapping-rain-water) - _Trapping Rain Water_ - _[check the task](https://neetcode.io/problems/trapping-rain-water)_ \ No newline at end of file diff --git a/src/neetcode/two-pointers/trapping-rain-water/solution.test.ts b/src/neetcode/two-pointers/trapping-rain-water/solution.test.ts new file mode 100644 index 0000000..2a85ea6 --- /dev/null +++ b/src/neetcode/two-pointers/trapping-rain-water/solution.test.ts @@ -0,0 +1,8 @@ +import { trap } from './solution'; + +describe('Trapping Rain Water | NeetCode | RoadMap | Testcases', () => { + test('#1', () => { + const height = [0, 2, 0, 3, 1, 0, 1, 3, 2, 1]; + expect(trap(height)).toBe(9); + }); +}); diff --git a/src/neetcode/two-pointers/trapping-rain-water/solution.ts b/src/neetcode/two-pointers/trapping-rain-water/solution.ts new file mode 100644 index 0000000..f8e316a --- /dev/null +++ b/src/neetcode/two-pointers/trapping-rain-water/solution.ts @@ -0,0 +1,30 @@ +/** + * @param {number[]} height - an array of non-negative integers which represent an elevation map. + * Each value `height[i]` represents the height of a bar, which has a width of `1`. + * @return {number} - the maximum area of water that can be trapped between the bars. + */ +export const trap = (height: number[]): number => { + if (height.length === 0) { + return 0; + } + + let l = 0; + let r = height.length - 1; + let lMax = height[l]; + let rMax = height[r]; + let res = 0; + + while (l < r) { + if (lMax < rMax) { + l++; + lMax = Math.max(lMax, height[l]); + res += lMax - height[l]; + } else { + r--; + rMax = Math.max(rMax, height[r]); + res += rMax - height[r]; + } + } + + return res; +};