455. Assign Cookies
贪心的本质是选择每一阶段的局部最优,从而达到全局最优
用最小的饼干先满足胃口最小的
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
index = 0
# 用最小的饼干先满足胃口最小的
for i in range(len(s)):
if index < len(g) and s[i] >= g[index]:
index += 1
return index
用最大的饼干先满足胃口最大的
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
i = len(g) - 1
j = len(s) - 1
count = 0
while i >= 0 and j >= 0:
if s[j] >= g[i]:
j -= 1
i -= 1
count += 1
else:
i -= 1
return count
376. Wiggle Subsequence
-
局部最优:删除单调坡度上的节点(不包括单调坡度两端的节点),那么这个坡度就可以有两个局部峰值。
-
整体最优:整个序列有最多的局部峰值,从而达到最长摆动序列。
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
prediff = 0 # 当前一对差值
curdiff = 0 # 前一对差值
res = 1 # 默认最右边有一个峰值
for i in range(len(nums) - 1):
curdiff = nums[i + 1] - nums[i]
if (curdiff < 0 and prediff >= 0) or (curdiff > 0 and prediff <= 0):
res += 1
prediff = curdiff
return res
53. Maximum Subarray
贪心
遍历nums,从头开始用count累积,如果count一旦加上nums[i]变为负数,那么就应该从nums[i+1]开始从0累积count了,因为已经变为负数的count,只会拖累总和
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
res = float('-inf')
curRes = 0
for i in range(len(nums)):
curRes += nums[i]
if curRes > res:
res = curRes
if curRes < 0: # 当前和<0,则立即抛弃
curRes = 0
return res
动态规划
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
if dp[i - 1] < 0:
dp[i] = nums[i]
else:
dp[i] = dp[i - 1] + nums[i]
return max(dp)