Skip to content

Commit f63c9fe

Browse files
committed
added trapping-rain-water.java code
1 parent cceb20a commit f63c9fe

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//Question : https://leetcode.com/problems/trapping-rain-water/description/
2+
3+
class Solution {
4+
public int trap(int[] h) {
5+
int n=h.length;
6+
7+
//left and ryt boundary
8+
int lb=h[0], rb=h[n-1];
9+
10+
//traversing range ,start and end within boundary
11+
int l=1, r= n-2;
12+
13+
int tw=0; //total_water
14+
15+
//traverse
16+
while(l<=r)
17+
{
18+
if(lb<=rb)
19+
{
20+
int hw=lb; //theight of water (smallest of(left and ryt boundary))
21+
22+
//whether water can be stored at top of building(h[l])
23+
if(h[l]<hw)
24+
{
25+
int ac= hw - h[l]; //actual height(i.e.. water on top of the building)
26+
tw+= ac; //add to total water
27+
}
28+
lb= Math.max(lb,h[l]);
29+
l++;
30+
}
31+
else
32+
{
33+
int hw=rb; //tot height of water
34+
35+
//whether water can be stored at top of building
36+
if(h[r]<hw)
37+
{
38+
int ac= hw - h[r]; //actual height(i.e.. water on top)
39+
tw+= ac; //add to total water
40+
}
41+
rb= Math.max(rb,h[r]);
42+
r--;
43+
}
44+
}
45+
return tw;
46+
47+
}
48+
}

0 commit comments

Comments
 (0)