算法第26天 | 贪心算法、455.分发饼干、376. 摆动序列、 53. 最大子序和

弹性算法理论基础

想清楚 局部最优 是什么,如果可以推导出全局最优,那就是正确的贪心算法

455. 分发饼干

题目

思路与解法

python 复制代码
class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        res = 0
        i = 0
        j = 0
        g.sort()
        s.sort()
        while i < len(s) and j < len(g):
            if s[i] >= g[j]:
                res += 1
                j += 1
            i += 1
        return res
            

376. 摆动序列

题目

思路与解法

没太懂,但是不想细想了

python 复制代码
class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
        if len(nums) <= 1:
            return len(nums)  # 如果数组长度为0或1,则返回数组长度
        curDiff = 0  # 当前一对元素的差值
        preDiff = 0  # 前一对元素的差值
        result = 1  # 记录峰值的个数,初始为1(默认最右边的元素被视为峰值)
        for i in range(len(nums) - 1):
            curDiff = nums[i + 1] - nums[i]  # 计算下一个元素与当前元素的差值
            # 如果遇到一个峰值
            if (preDiff <= 0 and curDiff > 0) or (preDiff >= 0 and curDiff < 0):
                result += 1  # 峰值个数加1
                preDiff = curDiff  # 注意这里,只在摆动变化的时候更新preDiff
        return result  # 返回最长摆动子序列的长度

53. 最大子序和

题目

思路与解法

python 复制代码
class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        res = float('-inf')
        count = 0

        for i in range(len(nums)):
            count += nums[i]
            if count > res:
                res = count
            if count < 0:
                count = 0

        return res
相关推荐
adam_life1 小时前
【P8306 【模板】字典树】
数据结构·算法·字典树·trie·哈希表··结构体
Wenhao.2 小时前
LeetCode Hot100 腐烂的橘子
算法·leetcode·职场和发展
行走的bug...2 小时前
支持向量机
算法·机器学习·支持向量机
信号处理学渣2 小时前
matlab之将一个升序数组按照元素值连续与否分成多组
数据结构·算法·matlab
大工mike2 小时前
代码随想录算法训练营第三十四天 | 198.打家劫舍 213.打家劫舍II 337.打家劫舍III
数据结构·算法·动态规划
用户992441031562 小时前
TRAE SOLO 赋能大模型工程化实践:从模型选型到安全部署的一站式实战指南
算法
goyeer2 小时前
05.[SAP ABAP] ABAP中的运算符
算法·sap·abap·运算符
NAGNIP3 小时前
面试官:BatchNorm、LayerNorm、GroupNorm、InstanceNorm 有什么本质区别?
算法·面试
Rock_yzh3 小时前
LeetCode算法刷题——560. 和为 K 的子数组
数据结构·c++·学习·算法·leetcode·职场和发展·哈希算法
水水不水啊3 小时前
通过一个域名,借助IPV6免费远程访问自己家里的设备
前端·python·算法