Fill a Cargo Hold for Maximum Value With Limited Item Supply
Greedy & IntervalsAuto-graded · 20 test casesLast updated
Tests whether a candidate can recognize that a bounded knapsack with uniform item weight reduces to a greedy sort-and-fill, handling large capacities and stock counts efficiently.
Problem
You are loading a cargo hold that has a fixed number of available pallet positions. Several product lines are available for shipping; each unit of any product takes up exactly one pallet position. Each product line i has a known profit per unit (values[i]) and a maximum available quantity (supply[i]). You cannot manufacture more units than what is in stock.
Decide how many units of each product to load so that the total pallet positions used stays within the hold's capacity, and the total profit is as large as possible.
Rules
- For each product line
i, choose a whole number of unitsx[i]satisfying0 <= x[i] <= supply[i]. - The sum of all chosen units must not exceed
hold_capacity. - Return the maximum achievable total profit. If nothing can be loaded (or loading nothing is optimal), return
0.
Constraints
1 <= len(values) == len(supply) <= 10^50 <= values[i] <= 10^61 <= supply[i] <= 10^90 <= hold_capacity <= 10^9- Total supply across all product lines can reach
10^14; the answer can reach roughly10^15. Both fit comfortably in a 64-bit integer (Python handles this natively).
Examples
Example 1
Input: max_cargo_profit([50, 90, 20], [3, 2, 100], 5)
Output: 330
Example 2
Input: max_cargo_profit([12, 0, 7], [1, 3, 999999999], 1000000000)
Output: 7000000005
Hints
Hint 1
If every unit costs the same amount of space regardless of which product it belongs to, what does that tell you about which units to load first?
Hint 2
Sort products by profit-per-unit descending, then fill the hold greedily — take as many units of the best product as stock and remaining space allow, then move on to the next best.
Hint 3
The loop runs at most n iterations no matter how large hold_capacity or any supply[i] is, so you never need a DP table proportional to the capacity.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why greedy is correct here
A classic bounded knapsack is NP-hard in general because items have different weights: a single heavy item might crowd out many lighter, collectively more valuable ones, so you have to consider all combinations.
That trade-off disappears completely when every unit has the same weight — here, exactly one pallet position. Because every slot costs the same regardless of which product fills it, you should always fill the next available slot with the highest-profit unit still in stock. Choosing anything other than the best available option for a slot cannot increase (and will often decrease) total profit.
A formal exchange argument confirms this: if an optimal loading uses a slot for a lower-value product while a higher-value product still has unused stock, swapping one unit for the other keeps the pallet count identical and increases (or at worst ties) total profit. So there is always an optimal solution that exhausts higher-value products before touching lower-value ones — and that is exactly what the greedy algorithm produces.
Algorithm
- Pair each product's value with its supply, then sort the pairs by value descending —
O(n log n). - Iterate through the sorted pairs, maintaining a
remainingbudget starting athold_capacity. For each product, loadmin(supply, remaining)units, add the resulting profit to a running total, and subtract those units fromremaining. - Stop early if
remainingreaches zero or if the current (and all subsequent) products have value zero, since they contribute nothing.
The loop body executes at most n times regardless of how large hold_capacity or any individual supply[i] is. This is the key advantage over a DP approach: a capacity-indexed DP table would require O(hold_capacity * n) time and space, which is completely infeasible for capacities up to 10^9.
Edge cases
hold_capacity == 0:remainingstarts at zero, so the early-exit fires immediately and the function returns0.- A product with
value == 0: the loop breaks as soon as it encounters one (since all subsequent products are also zero after sorting), and any units already loaded contribute nothing. Leaving zero-value slots empty is neither penalized nor rewarded. sum(supply) < hold_capacity: the hold never fills up; every unit of every (nonzero-value) product is loaded, and the loop exhausts the product list before the budget runs out.
Complexity
- Time:
O(n log n)dominated by the sort; the fill loop isO(n). - Space:
O(n)for the sorted list of pairs.
from typing import List
def max_cargo_profit(values: List[int], supply: List[int], hold_capacity: int) -> int:
remaining = hold_capacity
total = 0
for value, units in sorted(zip(values, supply), key=lambda pair: pair[0], reverse=True):
if remaining == 0 or value == 0:
break
take = min(units, remaining)
total += value * take
remaining -= take
return total