trapping-rain-water 1.0.0
Trapping Rain Water
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <iostream>
2#include <vector>
3
4using namespace std;
5
7{
8public:
9 int trap(vector<int>& height)
10 {
11 int total_volume = 0;
12 int left = 0; // left index
13 int right = height.size() - 1; // right index
14 int left_max = 0; // max height searching from left
15 int right_max = 0; // max height searching from right
16
17 // scan: left -->> <<-- right
18 while (left <= right)
19 {
20 if (height[left] <= height[right])
21 {
22 if (height[left] >= left_max) // update maximum height on the left
23 left_max = height[left];
24 else // add water volume
25 total_volume += left_max - height[left];
26 left++;
27 }
28 else
29 {
30 if (height[right] >= right_max) // update maximum height on the right
31 right_max = height[right];
32 else // add water volume
33 total_volume += right_max - height[right];
34 right--;
35 }
36 }
37 return total_volume;
38 }
39};
40
41int main()
42{
43 vector<int> terrain = {1,3,2,4,1,3,1,4,5,2,2,1,4,2,2}; // expected 15
44 // vector<int> terrain = {0,1,0,2,1,0,1,3,2,1,2,1}; // expected 6
45 // vector<int> terrain = {4,2,0,3,2,5}; // expected 9
46 Solution sol;
47 cout << "Volume of the lakes: " << sol.trap(terrain) << endl;
48 return 0;
49}
int trap(vector< int > &height)
Definition main.cpp:9
int main()
Definition main.cpp:41