maxLeft[0] = height[0]; for (int i = 1; i < height.size(); i++) maxLeft[i] = max(maxLeft[i - 1], height[i]);
maxRight[height.size() - 1] = height.back(); for (int i = height.size() - 2; i >= 0; i--) maxRight[i] = max(maxRight[i + 1], height[i]);
int sum = 0; for (int i = 0; i < height.size(); i++) { int count = min(maxLeft[i], maxRight[i]) - height[i]; if (count > 0) sum += count; } return sum; } };
classSolution { public: inttrap(vector<int>& height){ if (height.size() <= 2) return0; stack<int> st; st.push(0); int sum = 0; for (int i = 1; i < height.size(); i++) { if (height[i] <= height[st.top()]) st.push(i); else { while (!st.empty() && height[i] > height[st.top()]) { int mid = st.top(); st.pop(); if (!st.empty()) { int h = min(height[st.top()], height[i]) - height[mid]; int w = i - st.top() - 1; sum += h * w; } } st.push(i); } } return sum; } };