Fixed-Quota Task Reward Maximization
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You have n separate work items that must be split between two operators, Operator 1 and Operator 2:
- Every item
i(0 <= i < n) goes to one of the two operators. - Giving item
ito Operator 1 addsreward1[i]to the combined score, while giving itemito Operator 2 addsreward2[i]. - Operator 1 must receive a fixed quota of
kitems (0 <= k <= n), and Operator 2 receives the remainingn - kitems. - Any
kitem indices may be selected for Operator 1 (the chosen indices need not be adjacent).
Compute and return the largest combined score attainable across all n items.
Examples
Example 1
Input: reward1 = [8, 3, 6, 5], reward2 = [2, 9, 4, 7], k = 2
Output: 30
Walk-through: Give indices 0 (8) and 2 (6) to Operator 1, and indices 1 (9) and 3 (7) to Operator 2, earning 8 + 9 + 6 + 7 = 30. No other choice of 2 items for Operator 1 achieves more than 30.
Example 2
Input: reward1 = [4, 2, 5], reward2 = [6, 8, 5], k = 2
Output: 17
Walk-through: Even though Operator 1 never outscores Operator 2 on any item, Operator 1's quota of 2 items is mandatory. Assigning indices 0 (4) and 2 (5) to Operator 1 and keeping index 1 (8) for Operator 2 minimizes the point drop and yields 4 + 8 + 5 = 17.
Example 3
Input: reward1 = [10, 12, 9], reward2 = [3, 5, 4], k = 0
Output: 12
Walk-through: When k = 0, Operator 1 takes zero items and Operator 2 handles all three, scoring 3 + 5 + 4 = 12.
Constraints
0 <= n <= 10^5, wheren == len(reward1) == len(reward2)0 <= k <= n-10^9 <= reward1[i], reward2[i] <= 10^9
Step-by-step walkthrough
Understand the goal and the greedy trap
We have
nseparate work items and two operators:- Giving item
ito Operator 1 earnsreward1[i]points. - Giving item
ito Operator 2 earnsreward2[i]points. - Every item goes to one operator, and Operator 1 must receive a fixed quota of
kitems (leavingn - kitems for Operator 2).
A tempting first instinct is: "Just give Operator 1 the
kitems with the largestreward1values!" Let's test that instinct on 3 items withk = 1:Item index: 0 1 2 reward1: [10, 9, 1] reward2: [10, 1, 1] If Operator 1 takes Item 0 (highest reward1 = 10): total = 10 (Item 0) + 1 (Item 1) + 1 (Item 2) = 12 If Operator 1 takes Item 1 (reward1 = 9): total = 10 (Item 0) + 9 (Item 1) + 1 (Item 2) = 20 <-- much higher!Looking at
reward1alone ignores what we give up from Operator 2. On Item 0, Operator 2 already scores10, so putting Operator 1 there adds0net points. On Item 1, Operator 1 beats Operator 2 by8points!- Giving item
Why trying every subset of k items is too slow
A brute-force search generates every possible group of
kindices for Operator 1 and evaluates the total score for each group:import itertools def brute_force(reward1: List[int], reward2: List[int], k: int) -> int: n = len(reward1) best = None for chosen in itertools.combinations(range(n), k): picked = set(chosen) total = 0 for i in range(n): if i in picked: total += reward1[i] else: total += reward2[i] if best is None or total > best: best = total return bestThe number of ways to pick
kitems out ofnexplodes combinatorially: even forn = 40andk = 20, there are over137 billionsubsets. Withnup to100,000, we need an approach that finishes inO(n log n)time or faster.Key idea: start with Operator 2 and measure each switch gain
Instead of deciding both operators simultaneously, start from one clean baseline: give all
nitems to Operator 2 first.That baseline guarantees:
base_reward = reward2[0] + reward2[1] + ... + reward2[n - 1]Now ask: how does the combined score change if we switch one item
ifrom Operator 2 over to Operator 1?- We lose
reward2[i](Operator 2 no longer handles itemi). - We gain
reward1[i](Operator 1 now handles itemi).
So switching item
ichanges our combined score by a single number:switch_gains[i] = reward1[i] - reward2[i]Because the items do not interact with one another, switching any set
Sofkitems changes the baseline score by the sum of theirkindividualswitch_gains:total_reward(S) = base_reward + sum(switch_gains[i] for i in S)Notice what just happened:
base_rewardis a fixed constant! Two numbers per item collapsed into one number per item.- We lose
Sort the switch gains and pick the top k
To make
base_reward + sum of k chosen switch_gainsas large as possible, we pick theklargest numbers inswitch_gains.What if some (or all) values in
switch_gainsare negative, as in Example 2?- A negative
switch_gains[i]means Operator 1 earns fewer points on itemithan Operator 2 does. - Because Operator 1's quota of
kitems is fixed (not at mostk), we are still required to makekswitches. Picking the largest (least negative) values loses the fewest points possible.
Sorting
switch_gainsin descending order places the bestkswitches at indices0throughk - 1:def max_total_reward(reward1: List[int], reward2: List[int], k: int) -> int: # Phase 1: Establish a baseline by giving all n items to operator 2 first. base_reward = sum(reward2) # switch_gains: list of ints, e.g. [6, -6, 2, -2], where switch_gains[i] is the net # score change (reward1[i] - reward2[i]) if item i is switched to operator 1. switch_gains: List[int] = [] for task_idx in range(len(reward1)): net_change = reward1[task_idx] - reward2[task_idx] switch_gains.append(net_change) # Phase 2: Sort largest-first so the biggest gains (or smallest losses) sit at the front. switch_gains.sort(reverse=True) # Phase 3: Operator 1 must take a fixed quota of k items, even when some of the top k # gains are negative; when k == 0, range(0) skips the loop and keeps base_reward. total_reward = base_reward for pick_idx in range(k): total_reward += switch_gains[pick_idx] return total_reward- A negative
Trace Example 1 step by step
Walk through
reward1 = [8, 3, 6, 5],reward2 = [2, 9, 4, 7], andk = 2:Item index i : 0 1 2 3 reward1[i] : 8 3 6 5 reward2[i] : 2 9 4 7 ------------------------------------------------------- switch_gains : 8-2=6 3-9=-6 6-4=2 5-7=-2 1. Baseline (Operator 2 takes all 4 items): base_reward = 2 + 9 + 4 + 7 = 22 2. Sort switch_gains descending: [6, 2, -2, -6] 3. Add the first k = 2 switch gains: total_reward = 22 + 6 + 2 = 30Checking against the concrete split: Operator 1 takes Item 0 (
8) and Item 2 (6), while Operator 2 keeps Item 1 (9) and Item 3 (7), giving8 + 6 + 9 + 7 = 30.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def max_total_reward(reward1: List[int], reward2: List[int], k: int) -> int: # Phase 1: Establish a baseline by giving all n items to operator 2 first. base_reward = sum(reward2) # switch_gains: list of ints, e.g. [6, -6, 2, -2], where switch_gains[i] is the net # score change (reward1[i] - reward2[i]) if item i is switched to operator 1. switch_gains: List[int] = [] for task_idx in range(len(reward1)): net_change = reward1[task_idx] - reward2[task_idx] switch_gains.append(net_change) # Phase 2: Sort largest-first so the biggest gains (or smallest losses) sit at the front. switch_gains.sort(reverse=True) # Phase 3: Operator 1 must take a fixed quota of k items, even when some of the top k # gains are negative; when k == 0, range(0) skips the loop and keeps base_reward. total_reward = base_reward for pick_idx in range(k): total_reward += switch_gains[pick_idx] return total_reward✅ Submit now — all tests should pass.
Intuition & how it works
Think of this as giving all n items to Operator 2 on day one so you lock in a baseline score of sum(reward2), and then spending k mandatory "swap vouchers" to transfer k items over to Operator 1. Each swap carries an opportunity cost — a trade-off where gaining reward1[i] means giving up reward2[i] — so the net score change from swapping item i is reward1[i] - reward2[i]. Once every item is reduced to that single net-change number, maximizing the final sum is simply picking the k largest net changes.
A naive greedy strategy that picks the k items with the highest reward1 values fails because an item paying 10 to both operators gives zero net improvement over leaving it with Operator 2, whereas an item paying 9 to Operator 1 and 1 to Operator 2 nets +8. Meanwhile, a brute-force search over all C(n, k) subsets (where the binomial coefficient C(n, k) counts the ways to pick k items out of n) blows up exponentially, and a 2D dynamic programming table (storing best scores for every (item_index, chosen_count) pair) takes O(n * k) time — billions of operations when n = 100,000 and k = 50,000.
Here is how the swap-voucher idea plays out on Example 1 (reward1 = [8, 3, 6, 5], reward2 = [2, 9, 4, 7], k = 2):
- Baseline: Operator 2 takes all four items for
2 + 9 + 4 + 7 = 22points. - Net changes (
reward1[i] - reward2[i]):[8 - 2, 3 - 9, 6 - 4, 5 - 7] = [6, -6, 2, -2]. - Sort descending and take
k = 2: Sort[6, -6, 2, -2]into[6, 2, -2, -6]and add the first two values:22 + 6 + 2 = 30.
Complexity
- Time —
O(n log n): Summingreward2scansnnumbers (O(n)), buildingswitch_gainsscansnpairs (O(n)), sorting thengains takesO(n log n)comparisons, and adding the topkgains takesO(k) <= O(n)steps; sorting dominates. - Space —
O(n): We allocate one listswitch_gainsof lengthnto store the net difference for each item.
Edge cases
k = 0(Operator 1 gets zero items): The final loop runs zero times and returnssum(reward2).k = n(Operator 1 gets every item): Everyreward1[i] - reward2[i]gets added tosum(reward2), algebraically cancelingreward2and returningsum(reward1)even when Operator 2 would have scored higher.- Empty arrays (
n = 0, k = 0):sum([])is0and the loop runs zero times, returning0. - Non-positive switch gains (Example 2): Because Operator 1's quota
kis fixed, we still take theklargest (least negative) entries to minimize points lost. - Negative rewards in the input: Standard integer subtraction
reward1[i] - reward2[i]works identically whether individual rewards are positive, zero, or negative (for example-1 - (-4) = +3). - Ties in
switch_gains: Tied items change the total by the exact same amount, so picking any of them yields the same optimal score. - 64-bit integer sums in fixed-width languages: Python integers never overflow, whereas in C++ or Java
100,000items with rewards near10^9can reach10^14, requiring a 64-bitlong/long longaccumulator.
Common mistakes
- Sorting by
reward1[i]alone: Ignoresreward2[i]and wastes Operator 1's quota on items that Operator 2 already scores high on. - Stopping early when
switch_gainsturns negative: Adding only positive gains solves "give at mostkitems to Operator 1," violating the fixed-quota rule. - Sorting
reward1andreward2independently: Destroys the pairing betweenreward1[i]andreward2[i]for the same itemi. - Using an
O(n * k)dynamic programming table: Correct on tiny inputs, but runs out of time and memory whennandkare around10^5.
Alternative approaches
- Bounded min-heap (
heapq.nlargest(k, switch_gains)): A min-heap (a binary tree structure that keeps its smallest element at the root forO(log k)updates) can maintain just theklargest gains seen so far inO(n log k)time andO(k)space, which beats a full sort whenkis tiny or very close ton(by flipping roles whenk > n // 2). - Quickselect (selection in linear average time): Quickselect is a partitioning algorithm (like one-sided Quicksort) that places the
klargest elements on one side of a pivot inO(n)average time without sorting them relative to each other, though its worst-case time can degrade toO(n^2)unless median-of-medians pivoting is used.
Follow-up questions
- How would the algorithm change if the first operator's quota were 'at least k', 'at most k', or a range [lo, hi]? Sort
switch_gainsdescending just as before. For "at leastk," add the firstkgains unconditionally, then keep adding subsequent gains only whileswitch_gains[idx] > 0. For "at mostk," stop as soon as you have takenkitems orswitch_gains[idx] <= 0. A range[lo, hi]combines both rules: take the firstlounconditionally, then take positive gains up to indexhi - 1. - How can you reconstruct the exact subset of items assigned to each operator instead of returning only the optimal sum? Pair each net gain with its original index
(reward1[i] - reward2[i], i)before sorting descending. After sorting, slice the firstkindices for Operator 1 and give the remainingn - kindices to Operator 2; time and space remainO(n log n)andO(n). - What if you had to partition the n items across three operators with fixed quotas k1, k2, and k3? A single difference no longer orders the items because each item now has two independent trade-offs (
reward1[i] - reward3[i]andreward2[i] - reward3[i]), and greedily filling Operator 1 can steal an item where Operator 2 had an even larger advantage. Whennis moderate, dynamic programming over(item_idx, chosen_for_1, chosen_for_2)solves it inO(n * k1 * k2)time; for larger inputs, modeling items and operator capacities as a min-cost max-flow network (a graph algorithm that routes fixed supply to demand nodes at minimum cost or maximum reward) solves it in polynomial time.
Follow-up questions
- How would the algorithm change if the first operator's quota were 'at least k', 'at most k', or a range [lo, hi]?
- How can you reconstruct the exact subset of items assigned to each operator instead of returning only the optimal sum?
- What if you had to partition the n items across three operators with fixed quotas k1, k2, and k3?
Similar questions
- Per-Interval Overlap Counts on a Line
- Global Character Substitution Sequence
- Minimum Move-to-End Operations Between Strings
- Verify Unique Grid Placement of Target
- Shortest Grid Path via Breadth-First Search
- Unweighted Graph Distances and Shortest-Path Parents
More MathWorks interview questions
- Pointer Lifetimes, TLS over HTTP, and Transport Protocols Medium
- Cloud Identity and Session Authentication Service Medium
- SDET Internship Behavioral Interview Prompts Medium Pro
- Post-Coupon Order Totals with Sales Tax Medium Pro
- Piecewise Order Cost and Break-Even Volume Medium Pro
- Per-Interval Overlap Counts on a Line Medium Pro
- Hypergeometric Red Draw Probability Easy Pro
- Sequential Draw Probabilities and Expected Count Easy Pro
- Global Character Substitution Sequence Medium Pro
- Unique Grid Cell Under Spatial Constraints Hard Pro