[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
  • 数组
  • 双指针
  • 动态规划
  • 单调栈

  • 👍 4616
  • 👎 0
  • 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];
        }
    }
    
    posted @   shea24  阅读(9)  评论(0编辑  收藏  举报
    相关博文:
    阅读排行:
    · Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
    · 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
    · 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
    · 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
    · 【自荐】一款简洁、开源的在线白板工具 Drawnix
    点击右上角即可分享
    微信分享提示