KatInterview

Fill Bag with Maximum Value from Identical-Weight Items

Greedy & IntervalsAuto-graded · 21 test cases
MediumAuto-gradedGreedy & Intervalsgreedysortingoptimization

Last updated

Tests greedy optimization when all items have uniform weight, requiring recognition that standard knapsack DP is unnecessary and handling large counts efficiently.

You have a bag that can hold up to capacity units of weight. You're given n different item types, where each item type i has the following properties:

  • Every individual item of this type weighs exactly 1 unit
  • Every individual item of this type has value values[i]
  • You have counts[i] identical items of this type available

Your goal is to select items to place in the bag such that the total weight does not exceed capacity and the total value is maximized.

For each item type i, you may choose any number of items x[i] where 0 <= x[i] <= counts[i]. The total weight will be x[0] + x[1] + ... + x[n-1], which must not exceed capacity. The total value will be x[0] * values[0] + x[1] * values[1] + ... + x[n-1] * values[n-1].

Return the maximum total value achievable.

Constraints

  • 1 <= len(values) == len(counts) <= 10^5
  • 0 <= values[i] <= 10^6
  • 1 <= counts[i] <= 10^9
  • 0 <= capacity <= 10^9
  • The sum of all available items can reach 10^14
  • The maximum possible answer can reach 10^15, exceeding 32-bit integer limits

Examples

Example 1

Input: fill_bag_max_value([6, 10, 3], [2, 1, 5], 4)

Output: 25

Example 2

Input: fill_bag_max_value([4, 7], [3, 2], 10)

Output: 26

Example 3

Input: fill_bag_max_value([5, 0, 9], [1000000000, 3, 1], 1000000000)

Output: 5000000004

Hints

Hint 1

Since every item weighs exactly 1 unit, you're simply choosing at most capacity individual items to maximize value. Which items should you prioritize?

Hint 2

A greedy approach works here because uniform weights eliminate the typical knapsack trade-offs between heavy valuable items and light items.

Hint 3

Process item types in order of decreasing value, taking as many copies as possible from each type until capacity runs out.