算法记录 | Day31 贪心算法

455.分发饼干

优先满足大胃口

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        start, cout = len(s)-1, 0
        for i in range(len(g)-1, -1,-1):
            if start >= 0 and s[start]>=g[i]:
                cout+=1
                start-=1
        return cout

优先满足小胃口

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        res = 0
        for i in range(len(s)):
            if res < len(g) and s[i] >= g[res]:
                res += 1
        return res

376. 摆动序列

思路:

算法记录 | Day31 贪心算法_第1张图片观察图像可知,当不断交错的选择山脉的「波峰」和「波谷」作为子序列的元素,就会使摆动数组的子序列尽可能的长。

所以题目就变为了:统计序列中「峰」「谷」的数量。

记录下前一对连续项的差值、当前对连续项的差值,并判断是否是互为正负的。

  • 如果互为正负,则为「峰」或「谷」,记录下个数,并更新前一对连续项的差值。
  • 如果符号相同,则继续向后判断。
class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
        cur_diff = 0
        pre_diff = 0
        res = 1
        for i in range(len(nums)-1):
            cur_diff = nums[i+1] - nums[i]
            if (cur_diff>0 and pre_diff<=0) or (cur_diff<0 and pre_diff>=0):
                res += 1
                pre_diff = cur_diff
        return res

53. 最大子序和

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        res = -float('inf')
        cout = 0
        for i in range(len(nums)):
            cout +=  nums[i]
            if cout > res:
                res = cout
            if cout < 0:
                cout = 0
        return res

动态规划

参考链接:0053. 最大子数组和 | 算法通关手册 (itcharge.cn)

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

你可能感兴趣的:(leetcode,算法,leetcode,数据结构)