代码随想录算法训练营第30天

38 阅读1分钟

455.分发饼干

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort(reverse=True)
        s.sort(reverse=True)  # 对饼干大小和小孩胃口排序
        cnt = 0
        i = 0
        j = 0
        while i < len(g) and j < len(s):
            if s[j] >= g[i]:
                cnt += 1
                j += 1  # 分配饼干 j 给孩子 i
            i += 1  # 无论是否分配,都尝试下一个孩子
        return cnt

376.摆动序列

判断条件将等号放在prediff上,可以让第一个差值无论是正还是负都能被计入摆动序列

class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
        res=1;prediff=0;cur_diff=0
        if len(nums)<=1:
            return len(nums)
        for i in range(len(nums)-1):
            cur_diff=nums[i+1]-nums[i]
            if (cur_diff<0 and prediff>=0) or (cur_diff>0 and prediff<=0):
                res+=1
                prediff=cur_diff
        return res

最大子数组和

本题保留,还是用动态规划后面补做吧。。。