KatInterview

Fill a Cargo Hold for Maximum Value With Limited Item Supply

Greedy & IntervalsAuto-graded · 20 test cases
MediumAuto-gradedGreedy & Intervalsgreedysortingbounded-knapsack

Last 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 units x[i] satisfying 0 <= 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^5
  • 0 <= values[i] <= 10^6
  • 1 <= supply[i] <= 10^9
  • 0 <= hold_capacity <= 10^9
  • Total supply across all product lines can reach 10^14; the answer can reach roughly 10^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.