-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrappingRainWater.java
More file actions
42 lines (40 loc) · 1.07 KB
/
TrappingRainWater.java
File metadata and controls
42 lines (40 loc) · 1.07 KB
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
package CodingPatterns.TwoPointers;
/**
* Calculate water store in the given levels of heights.
*/
public class TrappingRainWater {
/**
* Get trapping water int.
*
* @param heights the heights
* @return the int
*/
public static int getTrappingWater(int heights[]){
int l = heights.length;
int left = 0; int right = l-1;
int maxRight = 0; int maxLeft = 0;
int water =0;
while(left<right){
if(heights[left]<heights[right]){
maxLeft = Math.max(maxLeft,heights[left]);
water+= maxLeft-heights[left];
left++;
}
else{
maxRight = Math.max(maxRight,heights[right]);
water+= maxRight-heights[right];
right--;
}
}
return water;
}
/**
* Main.
*
* @param args the args
*/
public static void main(String[] args){
int water[] = {3, 0, 1, 0, 4, 0, 2};
System.out.println("Water stored is :: "+getTrappingWater(water));
}
}