Skip to content

Commit e3115e3

Browse files
authored
Create TrappingRainWater.java
This Is An Easy Solution To The Hard Problem Of LeetCode 'Trapping RainWater' People Usually Get Scared To This Problem Because Of The Dynamic Programming Tag But I Have Solved This Using Two Arrays We Can Use Stack For Better Solution
1 parent 60a0435 commit e3115e3

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

TrappingRainWater.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
public int trap(int[] height) {
2+
int[] left = new int[height.length]; //for left most height for every tower
3+
int[] right = new int[height.length]; //for right most height for every tower
4+
int n = height.length;
5+
6+
int ctr = height[0];
7+
for(int i =0; i<n; i++){
8+
ctr = Math.max(ctr,height[i]);
9+
10+
left[i] = ctr;
11+
}
12+
13+
ctr = height[n-1];
14+
for(int i =n-1; i>=0; i--){
15+
ctr = Math.max(ctr,height[i]);
16+
right[i] = ctr;
17+
}
18+
int res = 0;
19+
20+
for(int i =0; i<n; i++){
21+
res += Math.min(left[i], right[i])-height[i];//water for every tower
22+
}
23+
24+
return res;
25+
}

0 commit comments

Comments
 (0)