Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. void sum_until_max(const vector<int> &height, int &water, const int max_index) {
  6.     int current_max = 0;
  7.     int i = 0;
  8.     for(i = 0; i < max_index; i++) {
  9.         current_max = max(current_max, height[i]);
  10.         water += current_max - height[i];
  11.     }
  12. }
  13.  
  14. int trap(vector<int> height) {
  15.     int n = height.size();
  16.     if (n == 0) {
  17.         return 0;
  18.     }
  19.     int max_index = 0;
  20.     for(int i = 0; i < n; i++) {
  21.         if(height[i] >= height[max_index]) {
  22.             max_index = i;
  23.         }
  24.     }
  25.     int water = 0;
  26.     sum_until_max(height, water, max_index);
  27.     reverse(height.begin(), height.end());
  28.     max_index = n - 1 - max_index;
  29.     sum_until_max(height, water, max_index);
  30.     return water;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement