一、开始进入贪心算法:
每一步都想着做到最好 想以此来达到全局最优的效果
1.leetcode题目 455. 分发饼干 - 力扣(LeetCode)
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
ans = 0
i = 0
j = 0
g.sort()
s.sort()
while i < len(g) and j < len(s):
if g[i]<=s[j]:
ans += 1
i += 1
j += 1
else:
j += 1
return ans
2.leetcode题目 376. 摆动序列 - 力扣(LeetCode)
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
if len(nums)<=1:
return len(nums)
curdiff = 0
prediff = 0
ans = 1
for i in range(1,len(nums)):
curdiff = nums[i] - nums[i-1]
if (curdiff>0 and prediff<=0) or (curdiff<0 and prediff>=0):
ans += 1
prediff = curdiff
return ans
3.leetcode题目 53. 最大子数组和 - 力扣(LeetCode)
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
cur_sum = 0
max_sum = -10**9
i = 0
while i < len(nums):
if cur_sum<0:
cur_sum = nums[i]
else:
cur_sum += nums[i]
max_sum = max(cur_sum,max_sum)
i += 1
return max_sum
(这些题目都是二刷了,感觉比第一次做起来顺手很多)