代码随想录算法训练营DAY31|理论基础、455.分发饼干、376. 摆动序列、53. 最大子序和

理论基础

贪心的本质是选择每一阶段的局部最优,从而达到全局最优

455.分发饼干

class Solution(object):
    def findContentChildren(self, g, s):
        """
        :type g: List[int]
        :type s: List[int]
        :rtype: int
        """
        g.sort(reverse=True)
        s.sort(reverse=True)
        count = 0
        i=0
        for j in range(len(s)):
            while i<len(g):
                if s[j]>=g[i]:
                    count+=1
                    i+=1
                    break
                else:
                    i=i+1
        
        return count
  • 从小到大index版
class Solution(object):
    def findContentChildren(self, g, s):
        """
        :type g: List[int]
        :type s: List[int]
        :rtype: int
        """
        g.sort()
        s.sort()
        count = 0
        index = len(s)-1
        for i in range(len(g)-1, -1, -1):
            if index>=0 and s[index]>=g[i]:
                count+=1
                index-=1
        return count

376.摆动序列

class Solution(object):
    def wiggleMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==1:
            return 1
        
        count=1
        for i in range(1,len(nums)-1):
            print(nums[i]-nums[i-1])
            if (nums[i]-nums[i-1])*(nums[i+1]-nums[i])<0:
                count+=1
            else:
                nums[i]=nums[i-1]
        if nums[len(nums)-1]-nums[len(nums)-2]!=0:
            count+=1
        return count
  • 这个版本相当于index=0时如果curdiff!=0则计数一次,就不会出现count少1的情况。
  • 且curdiff!=0才更新,不满足prediff*curdiff<=0(相当于取子数组)
class Solution(object):
    def wiggleMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """        
        if len(nums)<=1:
            return len(nums)

        count=1
        prediff,curdiff=0,0

        for i in range(len(nums)-1):
            curdiff=nums[i+1]-nums[i]
            if prediff*curdiff<=0 and curdiff!=0:
                count+=1
                prediff=curdiff

        return count

53. 最大子序和

  • 题目链接:53. 最大子数组和
  • 贪心:当tmp<0时则放弃当前数组,因为后面的数组加上tmp肯定是小于自身和的
  • 全负数用例(取最大负数):注意max_sum=最小负数,tmp先加再比较。
class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max_sum = float('-inf')
        tmp = 0
        for i in range(len(nums)):
            tmp+=nums[i]
            if tmp>max_sum:
                max_sum =tmp
            if tmp<0:
                tmp=0
        
        return max_sum
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值