算法训练 Day31

455.分发饼干

思路:贪心算法

解法1:贪心算法(大饼干对大胃口)

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        # method 1(大饼干对胃口大的)
        g.sort()
        s.sort()
        res = 0
        indx = len(s) - 1
        for i in range(len(g)-1,-1,-1):
            if indx >= 0 and s[indx] >= g[i]:
                res += 1
                indx -= 1
        return res
解法2: 贪心算法 小胃口对小饼干
class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        # method 2(小胃口对小饼干)
        g.sort()
        s.sort()
        indx = 0
        for i in range(len(s)):
            if indx <= len(g) -1  and s[i] >= g[indx]:
                indx += 1
        return indx

376. 摆动序列

解法:贪心算法

考虑情况:1.上下坡

                  2. 首位元素

                  3.单调平坡

class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
        if len(nums) == 1: return 1
        prediff = 0
        curdiff = 0
        res = 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):
                res += 1
                prediff = curdiff
        return res

53. 最大子序和

思路:动态规划

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        local_max = -inf
        global_max = nums[0]
        for val in nums:
            local_max = max(val, local_max+val)
            global_max = max(global_max, local_max)
        return global_max

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值