Skip to content

Commit 5f4661e

Browse files
authored
Merge pull request codewithdev#42 from alpha-neutr0n/master
Create trap_rain_water.cpp
2 parents 6c73cd3 + 838a2d4 commit 5f4661e

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
2+
3+
class Solution
4+
{
5+
public:
6+
int trap(vector<int>& height)
7+
{
8+
if (height.size() < 3) { return 0; }
9+
10+
// Get the indices of two highest bars, sort them and put into top2bars
11+
array<vector<int>::iterator, 2> top2bars;
12+
top2bars[0] = max_element(height.begin(), height.end());
13+
int tmp = *(top2bars[0]);
14+
*(top2bars[0]) = INT_MIN;
15+
top2bars[1] = max_element(height.begin(), height.end());
16+
int top2bars_min = *(top2bars[1]);
17+
*(top2bars[0]) = tmp;
18+
sort(top2bars.begin(), top2bars.end());
19+
20+
// Calculate the amount of water between the two highest bars
21+
int output = 0; // amount of trapped water
22+
for (auto it = top2bars[0] + 1; it < top2bars[1]; ++it)
23+
{
24+
output += top2bars_min - *it;
25+
}
26+
27+
// Call recursively trap() on bars left and right to the top2bars and add to the output
28+
vector<int>&& left = {height.begin(), top2bars[0] + 1};
29+
vector<int>&& right = {top2bars[1], height.end()};
30+
31+
return output + trap(left) + trap(right);
32+
}
33+
};

0 commit comments

Comments
 (0)