Mice and Cheese - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2
Output: 15
💡 Note: Mouse 1 should eat cheeses 2 and 3 (benefit differences +2 and +3). Mouse 2 gets cheeses 0 and 1. Total: 3 + 4 + 4 + 4 = 15
Example 2 — All to Mouse 1
$ Input: reward1 = [1,1], reward2 = [1,1], k = 2
Output: 2
💡 Note: Both cheeses have equal benefit for both mice, so mouse 1 eats all. Total: 1 + 1 = 2
Example 3 — Mouse 2 Better
$ Input: reward1 = [1,1,1], reward2 = [5,5,5], k = 1
Output: 11
💡 Note: Mouse 1 must eat exactly 1 cheese (any gives same result). Mouse 2 gets the other 2. Total: 1 + 5 + 5 = 11

Constraints

  • 1 ≤ reward1.length, reward2.length ≤ 105
  • 1 ≤ reward1[i], reward2[i] ≤ 1000
  • 0 ≤ k ≤ reward1.length

Visualization

Tap to expand
Mice and Cheese - Greedy Approach INPUT Mouse 1 Mouse 2 reward1: 1 1 3 4 [i=0,1,2,3] reward2: 4 4 1 1 k = 2 (Mouse 1 eats 2 cheeses) 4 Types of Cheese: 0 1 2 3 ALGORITHM STEPS 1 Calculate Difference diff[i] = reward1[i] - reward2[i] i: 0 1 2 3 diff: -3 -3 +2 +3 (1-4) (1-4) (3-1) (4-1) 2 Sort by Difference (DESC) Higher diff = better for Mouse 1 Sorted: [3, 2, 0, 1] diffs: +3 +2 -3 -3 3 Assign to Mouse 1 (k=2) First k indices from sorted Mouse 1: cheese[3]=4, cheese[2]=3 Points: 4 + 3 = 7 4 Assign to Mouse 2 Remaining cheeses Mouse 2: cheese[0]=4, cheese[1]=4 Points: 4 + 4 = 8 FINAL RESULT Cheese Assignment: Mouse 1 eats: 2 3 = 7 pts Mouse 2 eats: 0 1 = 8 pts TOTAL POINTS 7 + 8 = 15 Output: 15 OK - Maximum Achieved! Key Insight: The greedy strategy works because we want to maximize (reward1[i] - reward2[i]) for Mouse 1's choices. By sorting cheeses by this difference and giving Mouse 1 the top k, we ensure optimal point distribution. Time: O(n log n) for sorting | Space: O(n) for difference array TutorialsPoint - Mice and Cheese | Greedy - Sort by Benefit Difference
Asked in
Google 25 Amazon 18 Facebook 15
23.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen