KatInterview

Maximum Profit Under Capacity Constraint

Dynamic ProgrammingAuto-graded · 21 test cases
MediumAuto-gradedDynamic Programmingknapsackdynamic-programminggreedy

Last updated

Tests understanding of 0/1 knapsack disguised by a misleading ordering constraint that is actually always satisfiable.

You are optimizing a batch processing system. Each job has an associated profit and resource requirement. You are given:

  • profits: a list where profits[i] is the profit earned by completing job i
  • resources: a list where resources[i] is the amount of computational resources needed for job i
  • capacity: the total computational resources available

Your system can execute jobs in any order you choose, as long as you schedule them in non-decreasing order of their resource requirements. In other words, if you select a subset of jobs to run, you must be able to arrange them so that each job's resource requirement is at least as large as the previous job's.

Return the maximum total profit you can achieve by selecting and scheduling a valid subset of jobs whose total resource consumption does not exceed capacity.

Constraints

  • 1 <= len(profits) <= 1000
  • len(profits) == len(resources)
  • 0 <= profits[i] <= 10^6
  • 0 <= resources[i] <= 10^4
  • 0 <= capacity <= 10^4
  • All values are integers

Examples

Example 1

Input: max_profit_under_capacity([10, 20, 30], [1, 2, 3], 3)

Output: 30

Example 2

Input: max_profit_under_capacity([5, 10, 15], [3, 2, 1], 3)

Output: 25

Example 3

Input: max_profit_under_capacity([10, 20, 30], [5, 6, 7], 4)

Output: 0

Hints

Hint 1

The scheduling constraint sounds restrictive but is actually trivial: any subset of jobs can be scheduled by sorting them by resource requirement.

Hint 2

Since the ordering constraint is always satisfiable for any subset, the real question is: which subset maximizes profit while staying under capacity?

Hint 3

This is the classic 0/1 knapsack problem. Use dynamic programming with a 1D array, updating from high capacity to low to ensure each job is used at most once.