Input: values =[5,4,3,2,1], labels =[1,1,2,2,3], numWanted =3, useLimit
=1Output: 9Explanation:
The subset chosen is the first, third, and fifth items with the sum of values
5+3+1.
Input: values =[5,4,3,2,1], labels =[1,3,3,3,2], numWanted =3, useLimit
=2Output: 12Explanation:
The subset chosen is the first, second, and third items with the sum of values
5+4+3.
Input: values =[9,8,8,7,6], labels =[0,0,0,1,1], numWanted =3, useLimit
=1Output: 16Explanation:
The subset chosen is the first and fourth items with the sum of values 9+7.
To maximize the sum, always pick the largest available value, but do not exceed the useLimit for any label and do not pick more than numWanted items. Sorting by value allows us to greedily select the best items.
classSolution {
publicintlargestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) {
int n = values.length;
int[][] items =newint[n][2];
for (int i = 0; i < n; ++i) items[i]=newint[]{values[i], labels[i]};
Arrays.sort(items, (a, b) -> b[0]- a[0]);
Map<Integer, Integer> cnt =new HashMap<>();
int ans = 0, used = 0;
for (int[] it : items) {
int v = it[0], l = it[1];
if (cnt.getOrDefault(l, 0) < useLimit) {
ans += v;
cnt.put(l, cnt.getOrDefault(l, 0) + 1);
used++;
if (used == numWanted) break;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funlargestValsFromLabels(values: IntArray, labels: IntArray, numWanted: Int, useLimit: Int): Int {
val items = values.indices.map { values[it] to labels[it] }.sortedByDescending { it.first }
val cnt = mutableMapOf<Int, Int>()
var ans = 0var used = 0for ((v, l) in items) {
if ((cnt[l] ?:0) < useLimit) {
ans += v
cnt[l] = (cnt[l] ?:0) + 1 used++if (used == numWanted) break }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
deflargestValsFromLabels(self, values: list[int], labels: list[int], numWanted: int, useLimit: int) -> int:
items = sorted(zip(values, labels), reverse=True)
cnt = {}
ans = used =0for v, l in items:
if cnt.get(l, 0) < useLimit:
ans += v
cnt[l] = cnt.get(l, 0) +1 used +=1if used == numWanted:
breakreturn ans