Input: reward1 =[1,1,3,4], reward2 =[4,4,1,1], k =2Output: 15Explanation: In this example, the first mouse eats the 2nd(0-indexed) and the 3rd types of cheese, and the second mouse eats the 0th and the 1st types of cheese.The total points are 4+4+3+4=15.It can be proven that 15is the maximum total points that the mice can achieve.
Input: reward1 =[1,1], reward2 =[1,1], k =2Output: 2Explanation: In this example, the first mouse eats the 0th(0-indexed) and 1st types of cheese, and the second mouse does not eat any cheese.The total points are 1+1=2.It can be proven that 2is the maximum total points that the mice can achieve.
To maximize the total points, let the first mouse eat the k cheeses where the difference reward1[i] - reward2[i] is largest, and let the second mouse eat the rest. This ensures the first mouse gets the most beneficial cheeses.
classSolution {
public:int miceAndCheese(vector<int>& reward1, vector<int>& reward2, int k) {
int n = reward1.size();
vector<pair<int, int>> diff;
for (int i =0; i < n; ++i) diff.push_back({reward1[i] - reward2[i], i});
sort(diff.rbegin(), diff.rend());
int ans =0;
vector<bool> chosen(n, false);
for (int i =0; i < k; ++i) chosen[diff[i].second] = true;
for (int i =0; i < n; ++i) {
ans += chosen[i] ? reward1[i] : reward2[i];
}
return ans;
}
};
classSolution {
publicintmiceAndCheese(int[] reward1, int[] reward2, int k) {
int n = reward1.length;
int[][] diff =newint[n][2];
for (int i = 0; i < n; i++) diff[i]=newint[]{reward1[i]- reward2[i], i};
Arrays.sort(diff, (a, b) -> b[0]- a[0]);
int ans = 0;
boolean[] chosen =newboolean[n];
for (int i = 0; i < k; i++) chosen[diff[i][1]]=true;
for (int i = 0; i < n; i++) ans += chosen[i]? reward1[i] : reward2[i];
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funmiceAndCheese(reward1: IntArray, reward2: IntArray, k: Int): Int {
val n = reward1.size
val diff = Array(n) { i -> reward1[i] - reward2[i] to i }
diff.sortByDescending { it.first }
val chosen = BooleanArray(n)
for (i in0 until k) chosen[diff[i].second] = truevar ans = 0for (i in0 until n) ans +=if (chosen[i]) reward1[i] else reward2[i]
return ans
}
}
1
2
3
4
5
6
7
defmice_and_cheese(reward1: list[int], reward2: list[int], k: int) -> int:
n = len(reward1)
diff = sorted([(reward1[i] - reward2[i], i) for i in range(n)], reverse=True)
chosen = [False] * n
for i in range(k):
chosen[diff[i][1]] =Truereturn sum(reward1[i] if chosen[i] else reward2[i] for i in range(n))