-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathTrappingWater.java
More file actions
32 lines (26 loc) · 798 Bytes
/
TrappingWater.java
File metadata and controls
32 lines (26 loc) · 798 Bytes
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
package com.programs;
public class TrappingWater {
public static int trappingWater(int [] height) {
int leftMax[]=new int[height.length];
leftMax[0]=height[0];
for(int i=1;i<height.length;i++) {
leftMax[i]=Math.max(height[i], leftMax[i-1]);
}
int rightMax[]=new int[height.length];
rightMax[height.length-1]=height[height.length-1];
for(int i=height.length-2;i>=0;i--) {
rightMax[i]=Math.max(height[i], rightMax[i+1]);
}
int trappedWater=0;
for(int i=0;i<height.length;i++) {
int waterLevel=Math.min(leftMax[i], rightMax[i]);
trappedWater+=waterLevel-height[i];
}
return trappedWater;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] height= {4,2,0,6,3,2,5};
System.out.println(trappingWater(height));
}
}