-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLecture86.java
More file actions
26 lines (23 loc) · 756 Bytes
/
Lecture86.java
File metadata and controls
26 lines (23 loc) · 756 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
import java.util.Stack;
public class Lecture86 {
public static void main(String[] args) {
int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
System.out.println(trappedWater(arr, 12));
}
public static int trappedWater(int arr[], int n) {
int water = 0;
Stack<Integer> st = new Stack<>();
for (int i = 0; i < n; i++) {
while (!st.empty() && arr[st.peek()] < arr[i]) {
int index = st.pop();
int height = arr[index];
if (st.empty()) {
break;
}
water += ((Math.min(arr[st.peek()], arr[i]) - height) * (i - index));
}
st.push(i);
}
return water;
}
}