Approach

I was orginally thinking that we can colelct all the peaks, and fill the water between peaks, but finding that this might not be correct. For example like [2,0,1,0,1,0,2], if we fill between peaks, the 3-rd (0-indexed) would be 1, but it is actaully 2.

Later I come up with the idea for using mono stack. We collect all the points in increasing order, and try to fill from one to another. We also do the same thing backwards, since the mono-stack would stop on the largest element.

After my implementation, I found ony case that should do some more check, that is [2,0,2], when doing mono-stack with <, the middle 0 would not be put in either from front or back, so I modifed to <= for front case, and in this case we can complete this case, and also avoid duplicate countings.

Code

class Solution {
public:
    int trap(vector<int>& height) {
        // two way monotonic stack ..
        int fill = flood(height, true);
        reverse(height.begin(), height.end());
        fill += flood(height);
        return fill;
    }

    int flood(const vector<int>& height, bool front = false) {        
        int n = height.size();
        stack<pair<int, int>> stk1;
        stk1.push({height[0], 0});
        for(int i = 1 ; i < n ; ++i) {
            auto [maxVal, _] = stk1.top();
            if((front && height[i] >= maxVal) ||
                (!front && height[i] > maxVal)) {
                stk1.push({height[i], i});
            }
        }
        int fill = 0;
        while(stk1.size() >= 2) {
            auto [nextMax, nextIdx] = stk1.top();
            stk1.pop();
            auto [prevMax, prevIdx] = stk1.top();
            for(int i = prevIdx+1 ; i < nextIdx ; ++i) fill += (prevMax - height[i]);
        }
        return fill;
    }
};