-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path00042-trapping_rain_water.cpp
More file actions
51 lines (37 loc) · 931 Bytes
/
00042-trapping_rain_water.cpp
File metadata and controls
51 lines (37 loc) · 931 Bytes
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// 42: Trapping Rain Water
// https://leetcode.com/problems/trapping-rain-water/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
// SOLUTION
int trap(vector<int>& height) {
int l = 0;
int r = height.size() - 1;
int maxLeft = height[l];
int maxRight = height[r];
int result = 0;
while (l<r) {
if (maxLeft<=maxRight) {
l++;
maxLeft = max(maxLeft, height[l]);
result += maxLeft - height[l];
} else {
r--;
maxRight = max(maxRight, height[r]);
result += maxRight - height[r];
}
}
return result;
}
};
int main() {
Solution o;
// INPUT
vector<int> height = {4,2,0,3,2,5};
// OUTPUT
auto result = o.trap(height);
cout<<result<<endl;
return 0;
}