KatInterview

Maximum Reward Within a Spending Limit

Dynamic ProgrammingAuto-graded · 20 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingknapsackoptimization

Last 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 both cost and reward are 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) <= 1000
  • 0 <= cap <= 1000
  • 1 <= cost, reward <= 1000 for 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.