Skip to content

Commit 1d1b090

Browse files
authored
Create 42. Trapping Rain Water (#455)
2 parents ef9fd61 + 820ddf9 commit 1d1b090

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

42. Trapping Rain Water

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution
2+
{
3+
public:
4+
int trap(vector<int> &height)
5+
{
6+
int n = height.size(); // Number of elements in the input vector
7+
int water = 0; // Variable to store the total trapped water
8+
9+
// Arrays to store maximum height to the left and right of each index
10+
vector<int> l_max(n), r_max(n);
11+
12+
// Calculate the maximum height to the left of each index
13+
l_max[0] = height[0]; // First element's maximum height to the left is itself
14+
for (int i = 1; i < n; i++)
15+
l_max[i] = max(height[i], l_max[i - 1]);
16+
17+
// Calculate the maximum height to the right of each index
18+
r_max[n - 1] = height[n - 1]; // Last element's maximum height to the right is itself
19+
for (int i = n - 2; i >= 0; i--)
20+
r_max[i] = max(height[i], r_max[i + 1]);
21+
22+
// Iterate through each index (excluding the first and last)
23+
for (int i = 1; i < n - 1; i++)
24+
{
25+
// Calculate the maximum water current height can hold above itself
26+
water += min(r_max[i], l_max[i]) - height[i];
27+
}
28+
return water; // Return the total trapped water
29+
}
30+
};

0 commit comments

Comments
 (0)