-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path42.trapping-rain-water.java
More file actions
34 lines (31 loc) · 997 Bytes
/
42.trapping-rain-water.java
File metadata and controls
34 lines (31 loc) · 997 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
33
/*
* @lc app=leetcode id=42 lang=java
*
* [42] Trapping Rain Water
*/
// @lc code=start
class Solution {
public int trap(int[] height) {
int result = 0;
Stack<Integer> stack = new Stack<>();
//Remove the empty bar
int begin = 0;
while (begin < height.length && height[begin] == 0) {
begin++;
}
//Based on the idea of histogram, check problem 84.
for (int i = begin; i < height.length; i++) {
while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
int bottom = height[stack.pop()];
if (!stack.isEmpty()) {
//choose the minimum between left bound and right bound
int width = i - stack.peek() - 1;
result += Math.min(height[stack.peek()] - bottom, height[i] - bottom) * width;
}
}
stack.push(i);
}
return result;
}
}
// @lc code=end