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 i to Operator 1 adds reward1[i] to the combined score, while giving item i to Operator 2 adds reward2[i].
  • Operator 1 must receive a fixed quota of k items (0 <= k <= n), and Operator 2 receives the remaining n - k items.
  • Any k item 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, where n == len(reward1) == len(reward2)
  • 0 <= k <= n
  • -10^9 <= reward1[i], reward2[i] <= 10^9

Step-by-step walkthrough

  1. Understand the goal and the greedy trap

    We have n separate work items and two operators:

    • Giving item i to Operator 1 earns reward1[i] points.
    • Giving item i to Operator 2 earns reward2[i] points.
    • Every item goes to one operator, and Operator 1 must receive a fixed quota of k items (leaving n - k items for Operator 2).

    A tempting first instinct is: "Just give Operator 1 the k items with the largest reward1 values!" Let's test that instinct on 3 items with k = 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 reward1 alone ignores what we give up from Operator 2. On Item 0, Operator 2 already scores 10, so putting Operator 1 there adds 0 net points. On Item 1, Operator 1 beats Operator 2 by 8 points!

  2. Why trying every subset of k items is too slow

    A brute-force search generates every possible group of k indices 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 best
    

    The number of ways to pick k items out of n explodes combinatorially: even for n = 40 and k = 20, there are over 137 billion subsets. With n up to 100,000, we need an approach that finishes in O(n log n) time or faster.

  3. Key idea: start with Operator 2 and measure each switch gain

    Instead of deciding both operators simultaneously, start from one clean baseline: give all n items 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 i from Operator 2 over to Operator 1?

    • We lose reward2[i] (Operator 2 no longer handles item i).
    • We gain reward1[i] (Operator 1 now handles item i).

    So switching item i changes 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 S of k items changes the baseline score by the sum of their k individual switch_gains:

    total_reward(S) = base_reward + sum(switch_gains[i] for i in S)
    

    Notice what just happened: base_reward is a fixed constant! Two numbers per item collapsed into one number per item.

  4. Sort the switch gains and pick the top k

    To make base_reward + sum of k chosen switch_gains as large as possible, we pick the k largest numbers in switch_gains.

    What if some (or all) values in switch_gains are negative, as in Example 2?

    • A negative switch_gains[i] means Operator 1 earns fewer points on item i than Operator 2 does.
    • Because Operator 1's quota of k items is fixed (not at most k), we are still required to make k switches. Picking the largest (least negative) values loses the fewest points possible.

    Sorting switch_gains in descending order places the best k switches at indices 0 through k - 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
    
  5. Trace Example 1 step by step

    Walk through reward1 = [8, 3, 6, 5], reward2 = [2, 9, 4, 7], and k = 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 = 30
    

    Checking 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), giving 8 + 6 + 9 + 7 = 30.

  6. 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):

  1. Baseline: Operator 2 takes all four items for 2 + 9 + 4 + 7 = 22 points.
  2. Net changes (reward1[i] - reward2[i]): [8 - 2, 3 - 9, 6 - 4, 5 - 7] = [6, -6, 2, -2].
  3. 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): Summing reward2 scans n numbers (O(n)), building switch_gains scans n pairs (O(n)), sorting the n gains takes O(n log n) comparisons, and adding the top k gains takes O(k) <= O(n) steps; sorting dominates.
  • Space — O(n): We allocate one list switch_gains of length n to store the net difference for each item.

Edge cases

  • k = 0 (Operator 1 gets zero items): The final loop runs zero times and returns sum(reward2).
  • k = n (Operator 1 gets every item): Every reward1[i] - reward2[i] gets added to sum(reward2), algebraically canceling reward2 and returning sum(reward1) even when Operator 2 would have scored higher.
  • Empty arrays (n = 0, k = 0): sum([]) is 0 and the loop runs zero times, returning 0.
  • Non-positive switch gains (Example 2): Because Operator 1's quota k is fixed, we still take the k largest (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,000 items with rewards near 10^9 can reach 10^14, requiring a 64-bit long / long long accumulator.

Common mistakes

  • Sorting by reward1[i] alone: Ignores reward2[i] and wastes Operator 1's quota on items that Operator 2 already scores high on.
  • Stopping early when switch_gains turns negative: Adding only positive gains solves "give at most k items to Operator 1," violating the fixed-quota rule.
  • Sorting reward1 and reward2 independently: Destroys the pairing between reward1[i] and reward2[i] for the same item i.
  • Using an O(n * k) dynamic programming table: Correct on tiny inputs, but runs out of time and memory when n and k are around 10^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 for O(log k) updates) can maintain just the k largest gains seen so far in O(n log k) time and O(k) space, which beats a full sort when k is tiny or very close to n (by flipping roles when k > n // 2).
  • Quickselect (selection in linear average time): Quickselect is a partitioning algorithm (like one-sided Quicksort) that places the k largest elements on one side of a pivot in O(n) average time without sorting them relative to each other, though its worst-case time can degrade to O(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_gains descending just as before. For "at least k," add the first k gains unconditionally, then keep adding subsequent gains only while switch_gains[idx] > 0. For "at most k," stop as soon as you have taken k items or switch_gains[idx] <= 0. A range [lo, hi] combines both rules: take the first lo unconditionally, then take positive gains up to index hi - 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 first k indices for Operator 1 and give the remaining n - k indices to Operator 2; time and space remain O(n log n) and O(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] and reward2[i] - reward3[i]), and greedily filling Operator 1 can steal an item where Operator 2 had an even larger advantage. When n is moderate, dynamic programming over (item_idx, chosen_for_1, chosen_for_2) solves it in O(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

Similar questions

More MathWorks interview questions

All 23 MathWorks questions →