Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:
Input: height = [4,2,0,3,2,5] Output: 9
Constraints:
n == height.length0 <= n <= 3 * 1040 <= height[i] <= 105
Related Topics:
Array, Two Pointers, Dynamic Programming, Stack
Similar Questions:
- Container With Most Water (Medium)
- Product of Array Except Self (Medium)
- Trapping Rain Water II (Hard)
- Pour Water (Medium)
The water that can be held at position i is max(0, min(left[i], right[i]) - A[i]) where left[i] is the maximum height to the left of i and right[i] is the maximum height to the right of i.
// OJ: https://leetcode.com/problems/trapping-rain-water/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
int trap(vector<int>& A) {
int N = A.size(), ans = 0;
vector<int> left(N, 0), right(N, 0);
for (int i = 1; i < N; ++i) left[i] = max(left[i - 1], A[i - 1]);
for (int i = N - 2; i >= 0; --i) right[i] = max(right[i + 1], A[i + 1]);
for (int i = 1; i < N - 1; ++i) ans += max(0, min(left[i], right[i]) - A[i]);
return ans;
}
};Or
// OJ: https://leetcode.com/problems/trapping-rain-water/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
int trap(vector<int>& A) {
int N = A.size(), ans = 0, mx = 0, left = 0;
vector<int> right(N);
for (int i = N - 2; i >= 0; --i) right[i] = max(right[i + 1], A[i + 1]);
for (int i = 0; i < N; ++i) {
ans += max(0, min(left, right[i]) - A[i]);
left = max(left, A[i]);
}
return ans;
}
};Or use stack.
// OJ: https://leetcode.com/problems/trapping-rain-water/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
int trap(vector<int>& A) {
stack<int> right;
int N = A.size(), ans = 0, left = 0;
for (int i = N - 1; i >= 0; --i) {
if (right.empty() || A[i] > A[right.top()]) right.push(i);
}
for (int i = 0; i < N; ++i) {
if (right.top() == i) right.pop();
int h = min(left, right.size() ? A[right.top()] : 0);
ans += max(h - A[i], 0);
left = max(left, A[i]);
}
return ans;
}
};// OJ: https://leetcode.com/problems/trapping-rain-water/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int trap(vector<int>& A) {
if (A.empty()) return 0;
int N = A.size(), ans = 0, i = 0, j = N - 1, left = 0, right = 0;
while (i < j) {
if (A[i] < A[j]) {
left = max(left, A[i]);
ans += left - A[i++];
} else {
right = max(right, A[j]);
ans += right - A[j--];
}
}
return ans;
}
};