455. 分发饼干
class Solution:def findContentChildren(self, g: List[int], s: List[int]) -> int:g.sort(reverse=True)s.sort(reverse=True)j = 0for i in range(len(g)):if j <= len(s)-1 and s[j] >=g[i]:j +=1return j
376. 摆动序列
class Solution:def wiggleMaxLength(self, nums: List[int]) -> int:if len(nums) <=1:return len(nums)preC,curC = 0,0res = 1for i in range(len(nums)-1):curC = nums[i+1] -nums[i]if preC * curC <=0 and curC!=0:res +=1preC = curCreturn res
53. 最大子数组和
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)
1005. K 次取反后最大化的数组和
class Solution:def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:nums = sorted(nums,key=abs,reverse=True)for i in range(len(nums)):if k > 0:if nums[i] < 0:nums[i] = -1 * nums[i]k-=1else:breakif k >0:nums[-1] *= (-1)**kreturn sum(nums)
134. 加油站
class Solution:def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:all_count = 0cur_count = 0res = 0for i in range(len(gas)):all_count += gas[i] - cost[i]cur_count += gas[i] - cost[i]if cur_count < 0:cur_count = 0res = i+1if all_count >=0:return reselse:return -1
135. 分发糖果
class Solution:def candy(self, ratings: List[int]) -> int:dp = [1 for i in range(len(ratings))]for i in range(1,len(ratings)):if ratings[i] > ratings[i-1]:dp[i] = dp[i-1] + 1for i in range(len(ratings)-2,-1,-1):if ratings[i] > ratings[i+1]:dp[i] = max(dp[i+1]+1, dp[i])return sum(dp)
860. 柠檬水找零
class Solution:def lemonadeChange(self, bills: List[int]) -> bool:five = 0ten = 0for bill in bills:if bill ==5:five +=1elif bill==10:if five < 1:return Falsefive -=1ten +=1else:if ten > 0 and five >0:ten -=1five -=1elif five >2:five -=3else:return Falsereturn True
406. 根据身高重建队列
class Solution:def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:people.sort(key = lambda x :(-x[0],x[1]))que = []for p in people:que.insert(p[1],p)return que
452. 用最少数量的箭引爆气球
class Solution:def findMinArrowShots(self, points: List[List[int]]) -> int:points.sort() # 根据区间起点对区间进行升序排序,起点相同根据区间终点升序排序arrow = 0 # 使用箭数start, end = points[0] # 当前区间交集起点和终点,初始为首个区间起点和终点# 遍历每个区间,相同区间的交集为其本身,因此第一个区间的遍历不影响结果for (p_x, p_y) in points:if p_x > end:# 当前区间与当前区间交集没有交集,当前交集使用一个根箭;更新区间交集为当前区间arrow += 1start, end = p_x, p_yelse:# 当前区间与当前区间交集有交集,更新区间交集start = max(start, p_x)end = min(end, p_y)arrow += 1 # 最后一个区间交集还需要使用一根箭return arrow