代码随想录刷题第三十一天
贪心算法理论基础
分发饼干 (LC 455)
题目思路:
代码实现:
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
result = 0
index = 0
for i in range(len(g)):
while index<len(s) and s[index]<g[i]:
index+=1
if index<len(s) and s[index]>=g[i]:
result+=1
index+=1
return result
摆动序列 (LC 376)
题目思路:
代码实现:
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
if len(nums)==1:
return 1
prediff = 0
curdiff = 0
result = 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):
result+=1
prediff=curdiff
return result
最大子序和 (LC 53)
题目思路:
代码实现:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
result = -float("inf")
count = 0
for i in range(len(nums)):
count+=nums[i]
if count>result:
result = count
if count<0:
count = 0
return result