Maximum Reward Within a Spending Limit
Dynamic ProgrammingAuto-graded · 20 test casesLast updated
Tests whether a candidate can apply 0/1 knapsack dynamic programming to maximize total reward without exceeding a fixed spending cap.
Problem
You are planning a set of research experiments. Each experiment has a cost to run and produces a measurable reward. You have a fixed spending cap and can run each experiment at most once.
Given a list experiments where each element is a pair [cost, reward], and an integer cap representing the maximum total spending allowed, return the highest total reward achievable without exceeding the cap.
If no experiment can be run within the cap, return 0.
Input
experiments: a list of pairs[cost, reward], where bothcostandrewardare positive integers.cap: a non-negative integer representing the total spending limit.
Output
A single integer: the maximum total reward obtainable with total cost at most cap.
Constraints
1 <= len(experiments) <= 10000 <= cap <= 10001 <= cost, reward <= 1000for every experiment
Examples
Example 1
Input: max_reward_within_cap([[2, 10], [3, 15], [5, 40]], 6)
Output: 40
Example 2
Input: max_reward_within_cap([[1, 5], [2, 10], [3, 15]], 2)
Output: 10
Hints
Hint 1
Sorting by reward-to-cost ratio and picking greedily can fail here — think of a small counterexample to convince yourself, then consider why you need to evaluate combinations more systematically.
Hint 2
Define dp[w] as the best total reward reachable with total spending at most w. How does adding one new experiment change this table?
Hint 3
When updating dp[w] for a new experiment, which direction should you iterate over w — low to high, or high to low? Think about what value dp[w - cost] must represent at the moment you read it.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why greedy does not work
The first instinct is often to rank experiments by their reward-to-cost ratio and pick the best ones until the cap is exhausted. That strategy is optimal for the fractional version of the problem, where you can run part of an experiment. Here each experiment is all-or-nothing, so a locally attractive choice can crowd out a much better combination.
Quick counterexample with cap = 3:
| Experiment | Cost | Reward | Ratio |
|---|---|---|---|
| A | 1 | 2 | 2.0 |
| B | 3 | 5 | 1.67 |
Greedy picks A first (ratio 2.0), leaving only 2 units of budget. B no longer fits, so the total is 2. Picking B alone gives 5. Because items cannot be split, we have to consider combinations — and with up to 1000 experiments, brute-forcing all subsets is out of the question.
Dynamic programming state and recurrence
Define a 1-D array dp of length cap + 1, where dp[w] is the best total reward achievable using a subset of experiments whose total cost is at most w.
Initialize every entry to 0: with no experiments selected, the reward is zero regardless of the spending limit.
For each experiment (cost, reward), iterate w from cap down to cost and apply:
dp[w] = max(dp[w], dp[w - cost] + reward)
- The first option,
dp[w], represents skipping this experiment. - The second option,
dp[w - cost] + reward, represents running it: we spendcostunits, so we need a solution for the remaining budgetw - cost, then add this experiment's reward.
After processing all experiments, dp[cap] holds the answer.
Why iterate downward
When computing dp[w] for the current experiment, the read of dp[w - cost] must reflect the state before this experiment was considered — otherwise the same experiment could be counted more than once. Because w - cost < w, iterating from high to low guarantees that smaller indices have not yet been updated in the current pass. Iterating from low to high would let an update to a smaller index "contaminate" a later read, effectively allowing unlimited reuse of the same experiment (the unbounded knapsack variant).
Correctness argument
Invariant: after processing the first i experiments, dp[w] equals the best reward of any subset drawn from those i experiments with total cost at most w.
- Base case: with zero experiments the only subset is empty, reward is 0. The all-zeros initialization matches.
- Inductive step: any optimal subset of the first
iexperiments with cost at mostweither excludes experimentior includes it. Excluding it leaves the value unchanged at the olddp[w]. Including it means the remaining items form an optimal solution for the firsti-1experiments with budgetw - cost, whose value is the olddp[w - cost]. Taking the max of both cases gives the correct newdp[w], and descending iteration ensures both reads are "old" values.
Edge cases
cap = 0: the dp array has a single entrydp[0] = 0; the inner loop is always empty sincecost >= 1. Returns 0.- Empty
experiments: the outer loop never runs. Returnsdp[cap] = 0. - Every experiment costs more than
cap: the inner range is empty for every item. Returns 0. - An experiment whose cost equals
capexactly: the inner loop reachesw = cost, readsdp[0] = 0, and correctly setsdp[cap] = reward.
Complexity
- Time: O(n · B), where n is the number of experiments and B is the cap. In the worst case that is 1000 × 1000 = 10^6 operations.
- Space: O(B) for the single 1-D array, compared with O(n · B) for a full 2-D table.
The algorithm is pseudo-polynomial: its running time scales with the numeric value of cap, not with the number of bits needed to represent it. For very large caps (say, 10^9) this approach becomes impractical and alternatives such as meet-in-the-middle or DP over total reward should be considered.
Full solution
from typing import List
def max_reward_within_cap(experiments: List[List[int]], cap: int) -> int:
# dp[w] = best total reward using total cost <= w
dp = [0] * (cap + 1)
for cost, reward in experiments:
# Iterate downward so each experiment is counted at most once
for w in range(cap, cost - 1, -1):
dp[w] = max(dp[w], dp[w - cost] + reward)
return dp[cap]
Trace for experiments = [[2,10],[3,15],[5,40]], cap = 6:
| After experiment | dp[0..6] |
|---|---|
| (start) | 0, 0, 0, 0, 0, 0, 0 |
| [2, 10] | 0, 0, 10, 10, 10, 10, 10 |
| [3, 15] | 0, 0, 10, 15, 15, 25, 25 |
| [5, 40] | 0, 0, 10, 15, 15, 40, 40 |
dp[6] = 40.