Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)_
- [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)_
Original file line number Diff line number Diff line change
@@ -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);
});
});
30 changes: 30 additions & 0 deletions src/neetcode/two-pointers/trapping-rain-water/solution.ts
Original file line number Diff line number Diff line change
@@ -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;
};
Loading