forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main3.cpp
53 lines (39 loc) · 1.15 KB
/
main3.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/// Source : https://leetcode.com/problems/trapping-rain-water/description/
/// Author : liuyubobobo
/// Time : 2018-09-16
#include <iostream>
#include <vector>
using namespace std;
/// Dynamic Programming
///
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
int trap(vector<int>& height) {
if(height.size() <= 2)
return 0;
vector<int> rdp(height.size(), height.back());
for(int i = height.size() - 2; i >= 0; i --)
rdp[i] = max(height[i], rdp[i + 1]);
vector<int> ldp(height.size(), height[0]);
for(int i = 1; i < height.size(); i ++)
ldp[i] = max(height[i], ldp[i - 1]);
int res = 0;
for(int i = 0; i < height.size(); i ++)
res += min(ldp[i], rdp[i]) - height[i];
return res;
}
};
int main() {
vector<int> height1 = {0,1,0,2,1,0,1,3,2,1,2,1};
cout << Solution().trap(height1) << endl;
// 6
vector<int> height2 = {4,2,3};
cout << Solution().trap(height2) << endl;
// 1
vector<int> height3 = {4, 2, 0, 3, 2, 5};
cout << Solution().trap(height3) << endl;
// 9
return 0;
}