42. Trapping Rain Water
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6// Dynamic programming
int trap(vector<int>& height) { // time: O(n); space: O(n)
int res = 0, mx = 0, n = height.size();
vector<int> dp(n, 0);
// scan from left to right to record max left height
for (int i = 0; i < n; ++i) {
dp[i] = mx;
mx = max(mx, height[i]);
}
// reset mx to 0
mx = 0;
// scan from right to left to calculate res
for (int i = n - 1; i >= 0; --i) {
dp[i] = min(dp[i], mx); // record the minimum value between maxL and maxR
mx = max(mx, height[i]);
if (dp[i] > height[i]) res += dp[i] - height[i];
}
return res;
}Last updated
