aboutsummaryrefslogtreecommitdiff
path: root/trapping_rain_water.cpp
blob: d2ced43496d9605efa2815a2544aa7c055f7bab6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "leetcode.h"

class Solution {
public:
  int trap(vector<int> &height) {
    if (height.size() <= 2)
      return 0;
    int n = height.size(), maxLeft = height[0], maxRight = height[n - 1];
    int left = 1, right = n - 2, ans = 0;
    while (left <= right) {
      if (maxLeft < maxRight) {
        if (height[left] > maxLeft)
          maxLeft = height[left];
        else
          ans += maxLeft - height[left];
        left += 1;
      } else {
        if (height[right] > maxRight)
          maxRight = height[right];
        else
          ans += maxRight - height[right];
        right -= 1;
      }
    }
    return ans;
  }
};

int main() {
  Solution obj;
  vector<int> height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
  cout << obj.trap(height);
}