https://docs.pingcode.com/baike/1149749
import bisect a = [3,2,1] # 对于一个任意的数组 a.sort() # 先排序 k = 2 insert_index = bisect.bisect_left(range(len(a)),k,key = lambda x:a[x]) # 直接用这个函数进行查找 # insert_index 的结果是1,也就是说大于等于2的值的下标就是1。
对于不同的情况就按照下表来进行改变:

class Solution: def maxCapacity(self, costs: List[int], capacity: List[int], budget: int) -> int: a = [(cost,cap) for cost,cap in zip(costs,capacity) if cost<budget] a.sort(key=lambda x:x[0]) pre = [0]*(len(a)+1) for i,(cost,cap) in enumerate(a): pre[i+1] = max(cap,pre[i]) ans = 0 for i,(cost,cap) in enumerate(a): left = budget-cost j = bisect_left(range(i),left,key=lambda j:a[j][0]) ans = max(ans,cap+pre[j]) return ans
class Solution: def maxCapacity(self, costs: List[int], capacity: List[int], budget: int) -> int: a = [(cost,cap) for cost,cap in zip(costs,capacity) if cost<budget] a.sort(key=lambda x:x[0]) s = [(0,0)] ans = 0 for i,(cost,cap) in enumerate(a): while s[-1][0]+cost>=budget: s.pop() ans = max(ans,s[-1][1]+cap) if cap>s[-1][1]: s.append((cost,cap)) return ans
本文作者:Deshill
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!