image.png

    1. int trap(vector<int>& height)
    2. {
    3. int ans = 0, current = 0;
    4. stack<int> st;
    5. while (current < height.size()) {
    6. while (!st.empty() && height[current] > height[st.top()]) {
    7. int top = st.top();
    8. st.pop();
    9. if (st.empty())
    10. break;
    11. int distance = current - st.top() - 1;
    12. int bounded_height = min(height[current], height[st.top()]) - height[top];
    13. ans += distance * bounded_height;
    14. }
    15. st.push(current++);
    16. }
    17. return ans;
    18. }