classSolution { public: inttrap(vector<int>& height){ int n = height.size(); vector<int> leftMax(n); vector<int> rightMax(n); leftMax[0] = height[0]; rightMax[n-1] = height[n-1]; for(int i = 1;i < n-1;i++){ leftMax[i] = max(leftMax[i-1],height[i]); } for(int i = n-2;i > 0;i--){ rightMax[i] = max(rightMax[i+1],height[i]); }
int total = 0; for(int i = 1;i < n-1;i++){ int unit; // cout<< min(leftMax[i],rightMax[i])<<" "; unit = min(leftMax[i],rightMax[i])-height[i]; total += unit; } return total; } };
classSolution { public: inttrap(vector<int>& height){ stack<int> s; int ans = 0; int n = height.size(); for(int i = 0;i < n;i++){ while(!s.empty() && height[i] > height[s.top()]){ int top = s.top(); s.pop(); if(s.empty()){ break; } int left = s.top(); int width = i - left - 1; int h = min(height[i],height[left]) - height[top]; // cout<<width * h<<endl; ans += width * h; } s.push(i); } return ans; } };