455.分发饼干
思路:贪心算法
解法1:贪心算法(大饼干对大胃口)
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
# method 1(大饼干对胃口大的)
g.sort()
s.sort()
res = 0
indx = len(s) - 1
for i in range(len(g)-1,-1,-1):
if indx >= 0 and s[indx] >= g[i]:
res += 1
indx -= 1
return res
解法2:
贪心算法
小胃口对小饼干
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
# method 2(小胃口对小饼干)
g.sort()
s.sort()
indx = 0
for i in range(len(s)):
if indx <= len(g) -1 and s[i] >= g[indx]:
indx += 1
return indx
376. 摆动序列
解法:贪心算法
考虑情况:1.上下坡
2. 首位元素
3.单调平坡
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
if len(nums) == 1: return 1
prediff = 0
curdiff = 0
res = 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):
res += 1
prediff = curdiff
return res
53. 最大子序和
思路:动态规划
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
local_max = -inf
global_max = nums[0]
for val in nums:
local_max = max(val, local_max+val)
global_max = max(global_max, local_max)
return global_max