-
Notifications
You must be signed in to change notification settings - Fork 93
/
RainWaterBetweenTowers
36 lines (28 loc) · 1.06 KB
/
RainWaterBetweenTowers
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
package questions.saurabh;
public class RainWaterBetweenTowers {
public static int getMaxRainwaterBetweenTowers(int[] towerHeight) {
int maxSeenSoFar = 0;
int[] maxSeenRight = new int[towerHeight.length];
int maxSeenLeft = 0;
int rainwater = 0;
for (int i = towerHeight.length - 1; i >= 0; i--) {
if (towerHeight[i] > maxSeenSoFar) {
maxSeenSoFar = towerHeight[i];
maxSeenRight[i] = maxSeenSoFar;
} else {
maxSeenRight[i] = maxSeenSoFar;
}
}
for (int i = 0; i < towerHeight.length; i++) {
rainwater = rainwater + Integer.max(Integer.min(maxSeenLeft, maxSeenRight[i]) - towerHeight[i], 0);
if (towerHeight[i] > maxSeenLeft) {
maxSeenLeft = towerHeight[i];
}
}
return rainwater;
}
public static void main(String[] args) {
int[] towerHeight = { 1, 5, 2, 3, 1, 7, 2, 4 };
System.out.println(getMaxRainwaterBetweenTowers(towerHeight));
}
}