Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int trap(vector<int>& height) {
- if(height.empty()) {
- return 0;
- }
- stack<pair<int,int> > depth;
- int result = 0;
- auto ph = height[0];
- for(int i = 1; i < height.size(); ++i) {
- const auto h = height[i];
- if(h < ph) {
- depth.emplace(i - 1, ph - h);
- } else if (h > ph) {
- auto delta = h - ph;
- while(delta && !depth.empty()) {
- auto& d = depth.top();
- const auto actual = min(d.second, delta);
- d.second -= actual;
- delta -= actual;
- result += actual * (i - d.first - 1);
- if(d.second == 0) {
- depth.pop();
- }
- }
- }
- ph = h;
- }
- return result;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement