Opening the reading…
Opening the reading…
GREEDY › PART I
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Start with the only assignment that gives every cheese a default owner: let mouse two eat all n cheeses. This gives a base score equal to the sum of reward2[i]. The requirement that mouse one eats exactly k cheeses now means you must choose exactly k cheeses to move away from that baseline.
Moving cheese i from mouse two to mouse one changes the total by reward1[i] - reward2[i]. A positive difference improves the score, a negative difference reduces it, and a zero difference leaves it unchanged. Because every cheese contributes independently and the number of moves is fixed, the best assignment takes the k largest differences. No later choice can compensate for skipping a larger difference in favor of a smaller one.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n log n) | Building the baseline and all n differences takes linear time. Sorting the n differences takes O(n log n), and adding the first k values is O(k), which is at most O(n), so the sort dominates the total. |
| Space | O(n) extra | The diff array stores one value per cheese and is working memory; the scalar total and loop variables are O(1). The returned value is a single integer, so there is no output array to exclude. The extra space remains O(n) for every input shape. |
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
int miceAndCheese(vector<int>& reward1, vector<int>& reward2, int k) {
int n = reward1.size();
vector<int> diff(n);
int total = 0;
for (int i = 0; i < n; ++i) {
diff[i] = reward1[i] - reward2[i];
total += reward2[i];
}
sort(diff.rbegin(), diff.rend());
for (int i = 0; i < k; ++i) {
total += diff[i];
}
return total;
}
};The important placement is the subtraction before sorting. Sorting reward1 values alone ignores what mouse two would have earned from each cheese, while sorting reward1[i] - reward2[i] compares choices on equal footing. The loop adds exactly k differences, so even when every gain is negative, the method still obeys the required number of cheeses for mouse one.