Advertisement
Guest User

Untitled

a guest
Nov 21st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. class Solution {
  2. public:
  3. int trap(vector<int>& height) {
  4. if(height.empty()) {
  5. return 0;
  6. }
  7. stack<pair<int,int> > depth;
  8. int result = 0;
  9. auto ph = height[0];
  10. for(int i = 1; i < height.size(); ++i) {
  11. const auto h = height[i];
  12. if(h < ph) {
  13. depth.emplace(i - 1, ph - h);
  14. } else if (h > ph) {
  15. auto delta = h - ph;
  16. while(delta && !depth.empty()) {
  17. auto& d = depth.top();
  18. const auto actual = min(d.second, delta);
  19. d.second -= actual;
  20. delta -= actual;
  21. result += actual * (i - d.first - 1);
  22. if(d.second == 0) {
  23. depth.pop();
  24. }
  25. }
  26. }
  27. ph = h;
  28. }
  29. return result;
  30.  
  31. }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement