算法第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
相关推荐
田梓燊10 分钟前
算法题学习题单
学习·算法
Sunsets_Red15 分钟前
乘法逆元的 exgcd 求法
c++·学习·数学·算法·c#·密码学·信息学竞赛
阿Y加油吧18 分钟前
力扣打卡——接雨水、无重复字符的最长子串
算法·leetcode·职场和发展
handler0136 分钟前
算法:字符串哈希
c语言·数据结构·c++·笔记·算法·哈希算法·散列表
琪蘤40 分钟前
点胶换阀高度标定计算说明
算法
handler011 小时前
算法:查并集
开发语言·数据结构·c++·笔记·学习·算法·c
plus4s1 小时前
3月19日(进阶10)
算法
Trouvaille ~1 小时前
【优选算法篇】快速排序模型——从数组划分到快速选择
算法·leetcode·青少年编程·面试·蓝桥杯·快速排序·基础入门
Wect1 小时前
LeetCode 918. 环形子数组的最大和:两种解法详解
前端·算法·typescript