[LeetCode] Largest Values From Labels

1090. Largest Values From Labels

There is a set of n items. You are given two integer arrays values and labels where the value and the label of the ith element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit.

Choose a subset s of the n elements such that:

  • The size of the subset s is less than or equal to numWanted.
  • There are at most useLimit items with the same label in s.

The score of a subset is the sum of the values in the subset.

Return the maximum score of a subset s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int largestValsFromLabels(vector<int>& values, vector<int>& labels, int numWanted, int useLimit) {
vector<pair<int, int>> A;
int n = values.size(), res = 0;
for(int i = 0; i < n; i++) {
A.push_back({values[i], labels[i]});
}
sort(rbegin(A), rend(A));
unordered_map<int, int> freq;
for(int i = 0; i < n and numWanted; i++) {
auto [v, l] = A[i];
if(freq[l] == useLimit) continue;
res += v;
++freq[l];
--numWanted;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/30/PS/LeetCode/largest-values-from-labels/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.