List: 理论基础,455.分发饼干,376. 摆动序列,53. 最大子序和
理论基础,455.分发饼干assign-cookies,376. 摆动序列wiggle-subsequence,53. 最大子序和maximum-subarray
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
result = 0
index = len(s) - 1
for i in range(len(g) - 1, -1, -1):
if index >= 0 and s[index] >= g[i]:
result += 1
index -= 1
return result
顺序不能换:外面的 for 是里的下标 i 是固定移动的,而 if 里面的下标 index 是符合条件才移动的。如果 for 控制的是饼干, if 控制胃口,找不到。
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(s)):
if index < len(g) and s[i] >= g[index]:
result += 1
index += 1
return result
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
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