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

相关推荐
Wilber的技术分享14 分钟前
【LeetCode高频手撕题 2】面试中常见的手撕算法题(小红书)
笔记·算法·leetcode·面试
邪神与厨二病17 分钟前
Problem L. ZZUPC
c++·数学·算法·前缀和
软件测试媛1 小时前
软件测试常见的面试题(46道)
功能测试·面试·职场和发展
梯度下降中2 小时前
LoRA原理精讲
人工智能·算法·机器学习
IronMurphy2 小时前
【算法三十一】46. 全排列
算法·leetcode·职场和发展
czlczl200209252 小时前
力扣1911. 最大交替子序列和
算法·leetcode·动态规划
靴子学长2 小时前
Decoder only 架构下 - KV cache 的理解
pytorch·深度学习·算法·大模型·kv
寒秋花开曾相惜3 小时前
(学习笔记)3.8 指针运算(3.8.3 嵌套的数组& 3.8.4 定长数组)
java·开发语言·笔记·学习·算法
Гений.大天才3 小时前
2026年计算机领域的年度主题与范式转移
算法
njidf3 小时前
C++与Qt图形开发
开发语言·c++·算法