Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def maxCapacity(self, costs, capacity, budget):7 """8 :type costs: List[int]9 :type capacity: List[int]10 :type budget: int11 :rtype: int12 """13 mid = (budget-1)214 lookup = [0]*budget15 for i in xrange(len(costs)):16 if costs[i] >= budget:17 continue18 lookup[costs[i]] = max(lookup[costs[i]], capacity[i])19 for i in xrange(mid):20 lookup[i+1] = max(lookup[i+1], lookup[i])21 result = mx = 022 for i in xrange(len(costs)):23 if costs[i] > mid:24 continue25 result = max(result, mx+capacity[i])26 mx = max(mx, capacity[i])27 for i in xrange(mid+1, budget):28 result = max(result, lookup[i]+lookup[(budget-1)-i])29 return result30 31 32333435class Solution2(object):36 def maxCapacity(self, costs, capacity, budget):37 """38 :type costs: List[int]39 :type capacity: List[int]40 :type budget: int41 :rtype: int42 """43 result = 044 stk = []45 for i in sorted(xrange(len(costs)), key=lambda i: costs[i]):46 cost, cap = costs[i], capacity[i]47 if cost >= budget:48 break49 while stk and stk[-1][0]+cost >= budget:50 stk.pop()51 result = max(result, (stk[-1][1] if stk else 0)+cap)52 if not stk or stk[-1][1] < cap:53 stk.append((cost, cap))54 return result55 56 575859import bisect60 61 6263class Solution3(object):64 def maxCapacity(self, costs, capacity, budget):65 """66 :type costs: List[int]67 :type capacity: List[int]68 :type budget: int69 :rtype: int70 """71 def binary_search_right(left, right, check):72 while left <= right:73 mid = left+(right-left)274 if not check(mid):75 right = mid-176 else:77 left = mid+178 return right79 80 idxs = sorted(xrange(len(costs)), key=lambda i: costs[i])81 prefix = [0]*(len(idxs)+1)82 for i, idx in enumerate(idxs):83 prefix[i+1] = max(prefix[i], capacity[idx])84 result = 085 sorted_costs = [costs[i] for i in idxs]86 for i, idx in enumerate(idxs):87 cost, cap = costs[idx], capacity[idx]88 if cost >= budget:89 break90 j = bisect.bisect_left(sorted_costs, budget-cost, hi=i)-191 result = max(result, prefix[j+1]+cap)92 return result93 94 95969798class Solution4(object):99 def maxCapacity(self, costs, capacity, budget):100 """101 :type costs: List[int]102 :type capacity: List[int]103 :type budget: int104 :rtype: int105 """106 def binary_search_right(left, right, check):107 while left <= right:108 mid = left+(right-left)2109 if not check(mid):110 right = mid-1111 else:112 left = mid+1113 return right114 115 idxs = sorted(xrange(len(costs)), key=lambda i: costs[i])116 prefix = [0]*(len(idxs)+1)117 for i, idx in enumerate(idxs):118 prefix[i+1] = max(prefix[i], capacity[idx])119 result = 0120 for i, idx in enumerate(idxs):121 cost, cap = costs[idx], capacity[idx]122 if cost >= budget:123 break124 j = binary_search_right(0, i-1, lambda x: costs[idxs[x]]+cost < budget)125 result = max(result, prefix[j+1]+cap)126 return result127