-
Notifications
You must be signed in to change notification settings - Fork 0
/
RainDrop.java
32 lines (30 loc) · 1.02 KB
/
RainDrop.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
import java.util.Stack;
public class RainDrop {
public static void main(String[] args) {
int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
Stack<Integer> level = new Stack<Integer>();
int max = height[0];
int water = 0;
for (int i = 0; i < height.length; i++) {
if (height[i] > max) { //if new block is taller than the current tallest block, start popping
while (!level.empty()) {
water += max - level.pop();
}
max = height[i];
}
if (i == height.length - 1) { //if last block, reverse the popping
max = height[i];
while (!level.empty()) {
int h = level.pop();
if(h>max){
max = h;
} else {
water += max - h;
}
}
}
level.push(height[i]);
}
System.out.println(water);
}
}