Skip to content

Create 42. Trapping Rain Water #455

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions 42. Trapping Rain Water
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution
{
public:
int trap(vector<int> &height)
{
int n = height.size(); // Number of elements in the input vector
int water = 0; // Variable to store the total trapped water

// Arrays to store maximum height to the left and right of each index
vector<int> l_max(n), r_max(n);

// Calculate the maximum height to the left of each index
l_max[0] = height[0]; // First element's maximum height to the left is itself
for (int i = 1; i < n; i++)
l_max[i] = max(height[i], l_max[i - 1]);

// Calculate the maximum height to the right of each index
r_max[n - 1] = height[n - 1]; // Last element's maximum height to the right is itself
for (int i = n - 2; i >= 0; i--)
r_max[i] = max(height[i], r_max[i + 1]);

// Iterate through each index (excluding the first and last)
for (int i = 1; i < n - 1; i++)
{
// Calculate the maximum water current height can hold above itself
water += min(r_max[i], l_max[i]) - height[i];
}
return water; // Return the total trapped water
}
};
Loading