Problem solution · Python

Maximum Capacity Within Budget

Maximum Capacity Within Budget: a Python solution using binary search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Binary search
Source
Kamyu LeetCode Solutions
Length
127 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Binary search

For Maximum Capacity Within Budget, the implementation exploits a monotonic condition to discard half of the remaining search space after every check.

  1. Identify the ordered answer range or sorted search domain.
  2. Write a predicate whose truth changes only once.
  3. Move the appropriate boundary after each midpoint check and return the final feasible position.

Code notes

  • 127 lines of Python from the credited upstream file maximum-capacity-within-budget.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeMaximum Capacity Within Budget · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n + b)# Space: O(b) # hash table, prefix sumclass Solution(object):    def maxCapacity(self, costs, capacity, budget):        """        :type costs: List[int]        :type capacity: List[int]        :type budget: int        :rtype: int        """        mid = (budget-1)//2        lookup = [0]*budget        for i in xrange(len(costs)):            if costs[i] >= budget:                continue            lookup[costs[i]] = max(lookup[costs[i]], capacity[i])        for i in xrange(mid):            lookup[i+1] = max(lookup[i+1], lookup[i])        result = mx = 0        for i in xrange(len(costs)):            if costs[i] > mid:                continue            result = max(result, mx+capacity[i])            mx = max(mx, capacity[i])        for i in xrange(mid+1, budget):            result = max(result, lookup[i]+lookup[(budget-1)-i])        return result  # Time:  O(nlogn)# Space: O(n)# sort, mono stackclass Solution2(object):    def maxCapacity(self, costs, capacity, budget):        """        :type costs: List[int]        :type capacity: List[int]        :type budget: int        :rtype: int        """        result = 0        stk = []        for i in sorted(xrange(len(costs)), key=lambda i: costs[i]):            cost, cap = costs[i], capacity[i]            if cost >= budget:                break            while stk and stk[-1][0]+cost >= budget:                stk.pop()            result = max(result, (stk[-1][1] if stk else 0)+cap)            if not stk or stk[-1][1] < cap:                stk.append((cost, cap))        return result  # Time:  O(nlogn)# Space: O(n)import bisect  # sort, prefix sum, binary searchclass Solution3(object):    def maxCapacity(self, costs, capacity, budget):        """        :type costs: List[int]        :type capacity: List[int]        :type budget: int        :rtype: int        """        def binary_search_right(left, right, check):            while left <= right:                mid = left+(right-left)//2                if not check(mid):                    right = mid-1                else:                    left = mid+1            return right         idxs = sorted(xrange(len(costs)), key=lambda i: costs[i])        prefix = [0]*(len(idxs)+1)        for i, idx in enumerate(idxs):            prefix[i+1] = max(prefix[i], capacity[idx])        result = 0        sorted_costs = [costs[i] for i in idxs]        for i, idx in enumerate(idxs):            cost, cap = costs[idx], capacity[idx]            if cost >= budget:                break            j = bisect.bisect_left(sorted_costs, budget-cost, hi=i)-1            result = max(result, prefix[j+1]+cap)        return result  # Time:  O(nlogn)# Space: O(n)# sort, prefix sum, binary searchclass Solution4(object):    def maxCapacity(self, costs, capacity, budget):        """        :type costs: List[int]        :type capacity: List[int]        :type budget: int        :rtype: int        """        def binary_search_right(left, right, check):            while left <= right:                mid = left+(right-left)//2                if not check(mid):                    right = mid-1                else:                    left = mid+1            return right         idxs = sorted(xrange(len(costs)), key=lambda i: costs[i])        prefix = [0]*(len(idxs)+1)        for i, idx in enumerate(idxs):            prefix[i+1] = max(prefix[i], capacity[idx])        result = 0        for i, idx in enumerate(idxs):            cost, cap = costs[idx], capacity[idx]            if cost >= budget:                break            j = binary_search_right(0, i-1, lambda x: costs[idxs[x]]+cost < budget)            result = max(result, prefix[j+1]+cap)        return result 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗