File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments