【Day23】LeetCode:455. 分发饼干,376. 摆动序列,53. 最大子序和

文章目录

  • [LeetCode:455. 分发饼干](#LeetCode:455. 分发饼干)
  • [LeetCode:376. 摆动序列](#LeetCode:376. 摆动序列)
  • [LeetCode:53. 最大子序和](#LeetCode:53. 最大子序和)

LeetCode:455. 分发饼干

https://leetcode.cn/problems/assign-cookies/

思路

贪心算法,胃口最大的孩子匹配最大的饼干。从大到小遍历孩子的胃口:如果当前饼干能满足,则给出;否则直到找到第一个符合条件的孩子。

解答

python 复制代码
class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        len_g = len(g)
        len_s = len(s)

        g.sort()
        s.sort()

        results = 0
        idx_g = len_g - 1
        idx_s = len_s - 1 # s 的指针

        while idx_g >= 0: # 倒序遍历胃口
            if idx_s >= 0 and s[idx_s] >= g[idx_g]: # 将饼干匹配,遇到合适的就给出
                results += 1
                idx_s -= 1

            idx_g -= 1
            
        return results

LeetCode:376. 摆动序列

https://leetcode.cn/problems/wiggle-subsequence/description/

思路

如果一段子数组是单调递增的,那么其中任意两个元素的差都为正数,无法形成摆动。此时,我们只需保留该单调区间的第一个和最后一个元素,因为它们自然形成一个上升趋势和一个下降趋势的转折点。同理,如果一段子数组是单调递减的,只保留首尾。

如果存在重复元素,直接跳过。

解答

python 复制代码
class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
        n = len(nums)

        if n == 1 or (n == 2 and nums[0] != nums[1]): # 仅有一个元素或者含两个不等元素的序列
            return n

        results = 1 # 第一个元素默认计入
        pre_diff = 0

        for i in range(1, n):
            cur_diff = nums[i] - nums[i-1]
            if (cur_diff > 0 and pre_diff <= 0) or (cur_diff < 0 and pre_diff >= 0):
                results += 1
                pre_diff = cur_diff
            # cur_diff == 0 忽略,趋势不变

        return results

LeetCode:53. 最大子序和

https://leetcode.cn/problems/maximum-subarray/description/

思路

遍历数组,考量以 numsi 结尾的连续子数组的最大和,记作 cur_max。则有:

(1)将 nums[i] 加入之前的子数组,即 cur_max + nums[i] ;

(2)重新开始一个新的子数组,只包含 nums[i] 本身。

选择两者中较大的一个作为新的 cur_max ,同时更新 global_max 。

最后,global_max 即为答案。

解答

python 复制代码
class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        cur_max = global_max = nums[0]

        for num in nums[1:]: # 第一个元素既是当前最大,也是全局最大
            cur_max = max(num, cur_max + num) # 当前最大子数组要么是之前的最大子数组+当前值,要么从当前元素重新开始
            global_max = max(global_max, cur_max) # 更新全局最大子数组和

        return global_max
相关推荐
蜗牛互联网2 小时前
Python消费Responses SSE事件:增量文本、超时与取消
java·开发语言·人工智能·后端·python
wanderist.2 小时前
线性筛法详解:从筛质数到欧拉函数、Möbius 函数与约数函数
java·数据结构·算法
All for pursuit.2 小时前
【设计-1】208.实现Trie (前缀树)
数据结构·c++·算法·leetcode
statistican_ABin2 小时前
中国国际旅游发展分析报告—基于世界银行国际旅游数据的多维度分析
python·机器学习·旅游
weixin_307779132 小时前
C++代码实现MATLAB中的crossval函数功能
开发语言·c++·算法·matlab
青少儿编程课堂3 小时前
背包问题(0/1 背包与完全背包)解题精讲——动态规划入门
c++·python·算法·bfs·信息学竞赛
code2cat3 小时前
【随笔】MCP工具注解的信任边界:四个提示如何参与调用决策
python·ai agent·mcp
慢云智慧空间3 小时前
从设备智能到空间理解,慢云科技如何重新定义智慧建筑
python·科技
浮链序3 小时前
用 Claude Haiku 5.5 做子智能体路由,把 Agent 成本砍掉六成
人工智能·python·llm
冯一川3 小时前
安装Pyside 6
python