Skip to content

Commit 78cbde8

Browse files
authored
Merge pull request #147 from jayalloyd/feat/trapping-rain-water-on
feat(arrays): Add Trapping Rain Water O(n) solution
2 parents b0d4e42 + d355983 commit 78cbde8

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
public class TrappingRainWaterCode {
2+
public static int trappedRainWater(int height[]) {
3+
// auxilliary array
4+
// calculate left max boundary array
5+
int[] leftMaxBound = new int[height.length];
6+
leftMaxBound[0] = height[0];
7+
for (int i = 1; i < height.length; i++) {
8+
leftMaxBound[i] = Math.max(height[i], leftMaxBound[i - 1]);// i starts with 1 since we have already
9+
// calculated 0.compares current height with prev
10+
// leftmax boundary
11+
12+
}
13+
14+
// calculate right max boundary
15+
int[] rightMaxBound = new int[height.length];
16+
rightMaxBound[height.length - 1] = height[height.length - 1];// for last element rightmax boundary will be
17+
// itself
18+
for (int i = height.length - 2; i >= 0; i--) {
19+
rightMaxBound[i] = Math.max(height[i], rightMaxBound[i + 1]);
20+
21+
}
22+
int trappedWater = 0;
23+
// loop
24+
25+
for (int i = 1; i < height.length; i++) {
26+
// water level->mix(left max boundary,right max boundary)
27+
int waterLevel = Math.min(leftMaxBound[i], rightMaxBound[i]);
28+
29+
// trapped water->waterlevel-height[i]
30+
trappedWater += waterLevel - height[i];
31+
}
32+
return trappedWater;
33+
34+
}
35+
36+
public static void main(String[] args) {
37+
int[] height = { 4, 2, 0, 6, 3, 2, 5 };
38+
System.out.println(trappedRainWater(height));
39+
40+
}
41+
}
42+
/* time complexity->is proportional to number of bars */

0 commit comments

Comments
 (0)