10000 update array.js · khemssharma/leetcode@c9a851c · GitHub
[go: up one dir, main page]

Skip to content

Commit c9a851c

Browse files
committed
update array.js
1 parent e0195df commit c9a851c

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

array.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,30 @@ var maxArea = function (height) {
2828
}
2929
return maxWater
3030
};
31+
32+
// trapping rain water
33+
var trap = function(height) {
34+
if (height.length === 0) return 0;
35+
// two pointer and correspoding variables
36+
let left = 0, leftMax = 0;
37+
let right = height.length - 1, rightMax = 0;
38+
let waterTrapped = 0;
39+
while (left < right){
40+
if (height[left] < height[right]){
41+
if (height[left] >= leftMax){
42+
leftMax = height[left];
43+
}else{
44+
waterTrapped += leftMax - height[left]
45+
}
46+
left++;
47+
}else{
48+
if (height[right] >= rightMax){
49+
rightMax = height[right];
50+
}else{
51+
waterTrapped += rightMax - height[right]
52+
}
53+
right--;
54+
}
55+
}
56+
return waterTrapped;
57+
};

0 commit comments

Comments
 (0)
0