You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
> 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.
ans += min(left_max[i], right_max[i]) - heights[i];
128
+
}
129
+
return ans;
130
+
}
131
+
132
+
```
133
+
134
+
**Complexity Analysis**
135
+
136
+
- Time Complexity: $O(N)$
137
+
- Space Complexity: $O(N)$
138
+
139
+
## Two Pointers
140
+
141
+
### Solution
142
+
143
+
The above code is easy to understand, but it needs the extra space of N. We can tell from it that we in fact only cares about the minimum of (left[i], right[i]). Specifically:
144
+
145
+
- If l[i + 1] < r[i], the maximum in the left side of i will determine the height of trapping water.
146
+
- If l[i + 1] >= r[i], the maximum in the right side of i will determine the height of trapping water.
147
+
148
+
Thus, we don't need to keep two complete arrays. We can rather keep only a left max and a right max, using constant variable. This problem is a typical two pointers problem.
149
+
150
+
Algorithm:
151
+
152
+
1. Initialize two pointers `left` and `right`, pointing to the begin and the end of our height array respectively.
153
+
2. Initialize the left maximum height and the right maximum height to be 0.
154
+
3. Compare height[left] and height[right]
155
+
156
+
- If height[left] < height[right]
157
+
- 3.1.1 If height[left] >= left_max, the current trapping volume is (left_max - height[left])
158
+
- 3.1.2 Otherwise, no water is trapped and the volume is 0
159
+
- 3.2 Iterate the left pointer to the right
160
+
- 3.3 If height[left] >= height[right]
161
+
- 3.3.1 If height[right] >= right_max, the current trapping volume is (right_max - height[right])
162
+
- 3.3.2 Otherwise, no water is trapped and the volume is 0
For more solutions, visit my [LeetCode Solution Repo](https://github.com/azl397985856/leetcode) (which has 30K stars).
225
+
226
+
Follow my WeChat official account 力扣加加, which has lots of graphic solutions and teaches you how to recognize problem patterns to solve problems with efficiency.
0 commit comments