贪心开局:
局部最优堆叠成全局最优--模拟一下 举不出反例就用贪心
排序之后小饼干优先
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
idx=0
for i in range(len(s)):
if idx<len(g) and g[idx]<=s[i]:
idx+=1
return idx
大饼干满足大孩子
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
idx=len(s)-1
res=0
for i in range(len(g)-1,-1,-1):
if idx>=0 and s[idx]>=g[i]:
res+=1
idx-=1
return res
也不用什么移除,数弯就行,没有就过
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
if len(nums)<=1:return len(nums)
curdiff=0
prediff=0
res=1
for i in range(len(nums)-1):
curdiff=nums[i+1]-nums[i]
if curdiff*prediff<=0 and curdiff!=0:
res+=1
prediff=curdiff
return res
贪心的经典题 遇到负数重新算
属于是见过的套路题就记下来
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
res=float('-inf')
cnt=0
for i in range(len(nums)):
cnt+=nums[i]
if cnt>res:
res=cnt
if cnt<=0:#一旦总和为负 就重新来
cnt=0
return res