[LeetCode] Trapping Rain Water

42. Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

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
class Solution {
public:
int trap(vector<int>& height) {
stack<pair<int, int>> st;
int res = 0;
st.push({0, 1});
for(auto& h : height) {
if(st.top().first < h) {
unordered_map<int, int> m;
int maxHeight = 0, count = 0;
while(!st.empty() && maxHeight < h) {
m[st.top().first] += st.top().second;
maxHeight = max(maxHeight, st.top().first);
count += st.top().second;
st.pop();
}
if(maxHeight < h) {
st.push({h, 1});
} else {
st.push({maxHeight, m[maxHeight]});
st.push({h, count - m[maxHeight] + 1});
}
int trapHeight = min(maxHeight, h);
if(!trapHeight) continue;
for(auto entity : m) {
if(entity.first >= trapHeight) continue;
res += (trapHeight - entity.first) * entity.second;
}
} else {
st.push({h, 1});
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/07/12/PS/LeetCode/trapping-rain-water/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.