Mice and Cheese Problem
Description
LeetCode Problem 2611.
There are two mice and n different types of cheese, each type of cheese should be eaten by exactly one mouse.
A point of the cheese with index i (0-indexed) is:
reward1[i]if the first mouse eats it.reward2[i]if the second mouse eats it.
You are given a positive integer array reward1, a positive integer array reward2, and a non-negative integer k.
Return the maximum points the mice can achieve if the first mouse eats exactly k types of cheese.
Example 1:
Input: reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2
Output: 15
Explanation: In this example, the first mouse eats the 2^nd (0-indexed) and the 3^rd types of cheese, and the second mouse eats the 0^th and the 1^st types of cheese.
The total points are 4 + 4 + 3 + 4 = 15.
It can be proven that 15 is the maximum total points that the mice can achieve.
Example 2:
Input: reward1 = [1,1], reward2 = [1,1], k = 2
Output: 2
Explanation: In this example, the first mouse eats the 0^th (0-indexed) and 1^st types of cheese, and the second mouse does not eat any cheese.
The total points are 1 + 1 = 2.
It can be proven that 2 is the maximum total points that the mice can achieve.
Constraints:
1 <= n == reward1.length == reward2.length <= 10^51 <= reward1[i], reward2[i] <= 10000 <= k <= n
Solution
Approach: Greedy + Sort
Start by giving every piece of cheese to the second mouse. Handing piece i to the first mouse instead changes the total by reward1[i] - reward2[i]. The first mouse must take exactly k pieces, so pick the k pieces with the largest change.
Sort the indices by reward1[i] - reward2[i] in decreasing order. The first k pieces go to the first mouse, the rest go to the second mouse. Add up the rewards.
Complexity: O(n log n) time and O(n) space, where n is the number of pieces of cheese.
class Solution:
def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int:
n = len(reward1)
idx = sorted(range(n), key=lambda i: reward1[i] - reward2[i], reverse=True)
return sum(reward1[i] for i in idx[:k]) + sum(reward2[i] for i in idx[k:])