Leetcode-.42接雨水

动态规划,记录i数组前后缀的最大值

python 复制代码
class Solution:

    def trap(self, height: List[int]) -> int:

        n=len(height)

        pre_max=n*[0]

        pre_max[0]=height[0]

        for i in range(1,n):

            pre_max[i]=max(pre_max[i-1],height[i])

        suf_max=[0]*n

        suf_max[-1]=height[-1]

        for i in range (n-2,-1,-1):

            suf_max[i]=max(suf_max[i+1],height[i])

        ans=0

        for h,pre,suf in zip(height,pre_max,suf_max):

            ans+=min(pre,suf)-h
  
        return ans
  • pre_max[i]:表示从最左边到当前位置 i 为止的最大柱子高度;
    pre_max[i]=max⁡(height[0],height[1],...,height[i])pre\_max[i]=max⁡(height[0],height[1],...,height[i])pre_max[i]=max⁡(height[0],height[1],...,height[i])
  • suf_max[i]:表示从当前位置 i 到最右边 的最大柱子高度;
    suf_max[i]=max⁡(height[i],height[i+1],...,height[n−1])suf\_max[i]=max⁡(height[i],height[i+1],...,height[n−1])suf_max[i]=max⁡(height[i],height[i+1],...,height[n−1])

对于下标 i,下雨后水能到达的最大高度等于下标 i 两边的最大高度的最小值,下标 i 处能接的雨水量等于下标 i 处的水能到达的最大高度减去 height[i]。

相关推荐
旖-旎28 分钟前
深搜练习(单词搜索)(12)
c++·算法·深度优先·力扣
企客宝CRM1 小时前
2026年中小企业CRM选型指南:企客宝CRM处于什么位置?
android·算法·企业微信·rxjava·crm
橙淮1 小时前
二叉树核心概念与Java实现详解
数据结构·算法
米罗篮2 小时前
DSU并查集 & 拓展欧几里得-逆元
c++·经验分享·笔记·算法·青少年编程
橙淮2 小时前
双指针法:高效算法解题的利器
算法
初心未改HD2 小时前
深度学习之MLP与反向传播算法详解
人工智能·深度学习·算法
刀法如飞2 小时前
【Go 字符串查找的 20 种实现方式,用不同思路解决问题】
人工智能·算法·go
程序员雷欧3 小时前
大厂OS面试高频题
面试·职场和发展
技术小黑4 小时前
CNN算法实战系列03 | DenseNet121算法实战与解析
pytorch·深度学习·算法·cnn