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]。

相关推荐
蜡笔小马4 分钟前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
我是咸鱼不闲呀9 分钟前
力扣Hot100系列20(Java)——[动态规划]总结(下)( 单词拆分,最大递增子序列,乘积最大子数组 ,分割等和子集,最长有效括号)
java·leetcode·动态规划
唐梓航-求职中13 分钟前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
仟濹15 分钟前
【算法打卡day3 | 2026-02-08 周日 | 算法: BFS】3_卡码网99_计数孤岛_BFS | 4_卡码网100_最大岛屿的面积DFS
算法·深度优先·宽度优先
Ll130452529818 分钟前
Leetcode二叉树part4
算法·leetcode·职场和发展
颜酱28 分钟前
二叉树遍历思维实战
javascript·后端·算法
宝贝儿好30 分钟前
第二章: 图像处理基本操作
算法
小陈phd41 分钟前
多模态大模型学习笔记(二)——机器学习十大经典算法:一张表看懂分类 / 回归 / 聚类 / 降维
学习·算法·机器学习
@––––––42 分钟前
力扣hot100—系列4-贪心算法
算法·leetcode·贪心算法
CoovallyAIHub1 小时前
让本地知识引导AI追踪社区变迁,让AI真正理解社会现象
深度学习·算法·计算机视觉