forked from pengsida/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode42.cpp
35 lines (33 loc) · 856 Bytes
/
leetcode42.cpp
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
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int trap(vector<int>& height) {
int max_id = 0;
for (int i = 0; i < height.size(); i++) {
if (height[i] > height[max_id])
max_id = i;
}
int ans = 0;
for (int i = 0; i < max_id; i++) {
int tmp = 0;
auto h = height[i];
while (height[i + 1] < h) {
tmp = tmp + h - height[i + 1];
i++;
}
ans += tmp;
}
for (int i = height.size() - 1; i > max_id; i--) {
int tmp = 0;
auto h = height[i];
while (height[i - 1] < h) {
tmp = tmp + h - height[i - 1];
i--;
}
ans += tmp;
}
return ans;
}
};