[LeetCode][42]trapping-rain-water
Content
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.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
Related Topics
Solution
1. 单调栈+动态规划
Java
class Solution {
public int trap(int[] height) {
// n == height.length
// 1 <= n <= 2 * 10⁴
// 0 <= height[i] <= 10⁵
int n = height.length;
// 单调递减栈
int[] stack = new int[n];
int top = 0;
// 累加bar
int[] sums = new int[n];
sums[0] = height[0];
for (int i = 1; i < n; i++) {
sums[i] = sums[i - 1] + height[i];
}
// dp[i]表示以下标i所对应的bar作为最右边的bar时,能trap多少雨水。
int[] dp = new int[n];
for (int i = 1; i < n; i++) {
if (height[i - 1] >= height[i]) {
stack[++top] = i;
dp[i] = dp[i - 1];
} else {
while (top > 0 && height[stack[top]] < height[i]) {
top--;
}
dp[i] = dp[stack[top]]
+ Math.min(height[stack[top]], height[i]) * (i - stack[top] - 1)
- (sums[i - 1] - sums[stack[top]]);
if (height[stack[top]] >= height[i]) {
stack[++top] = i;
} else {
stack[top] = i;
}
}
}
return dp[n - 1];
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix