-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathTrappingRainWater.java
48 lines (40 loc) · 1.23 KB
/
TrappingRainWater.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Created by achoudhary on 06/01/2016.
*/
public class TrappingRainWater {
public int trap(int[] height) {
if(height.length == 0)
return 0;
int output = 0;
int[] leftMax = new int[height.length]; //hold the max left value
int[] rightMax = new int[height.length]; //holds the right max value for any ith element
int max = height[0];
/**
* iterate through ascending order to track maxLeft element
* for each ith Element
*/
for (int i = 1; i < height.length; i++) {
leftMax[i] = max;
if(height[i] > max){
max = height[i];
}
}
/**
* iterate through descending order to track maxRight element
* for each ith Element
*/
max = height[height.length-1];
for (int i = height.length-2; i >= 0; i--) {
rightMax[i] = max;
if(height[i] > max){
max = height[i];
}
}
for (int i = 1; i < height.length - 1; i++) {
int trap = Math.min(leftMax[i], rightMax[i]) - height[i];
if (trap > 0)
output += trap;
}
return output;
}
}