knakul853

Untitled

Jul 17th, 2020
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4. class Solution {
  5. public:
  6.     int trap(vector<int>& height) {
  7.        
  8.         if(height.empty()) return 0;
  9.        
  10.         int n = (int)height.size();
  11.         vector<int>pre(n, -1);
  12.         vector<int>suf(n, -1);
  13.        
  14.         pre[0] = 0;
  15.         for(int i=1;i<n;i++)
  16.         {
  17.             pre[i] = max(pre[i-1], height[i-1]);
  18.         }
  19.        
  20.         suf[n-1] = 0;
  21.         for(int i=n-2;i>=0;i--)
  22.         {
  23.             suf[i] = max(suf[i+1], height[i+1]);
  24.         }
  25.        
  26.         int ans = 0;
  27.        
  28.        
  29.         for(int i=1;i<n-1;i++)
  30.         {
  31.             int mn = min(suf[i], pre[i]);
  32.            
  33.             if(mn == 0 )continue;
  34.             if(mn > height[i])
  35.             ans += mn - height[i];
  36.         }
  37.        
  38.         return ans;
  39.        
  40.     }
  41. };
Add Comment
Please, Sign In to add comment