Largest Values From Labels LeetCode solution in C++

1
class Solution {
2
public:
3
int largestValsFromLabels(vector<int> &values, vector<int> &labels, int numWanted, int useLimit) {
4
// same label item should be less than uselimit
5
priority_queue<pair<int, int>> q; // this will give us maximum element
6
// because we need to maximise the sum
7
for (int i = 0; i < values.size(); i++) {
8
q.push({values[i], i});
9
}
10
long long int ans = 0;
11
unordered_map<int, int> m;
12
// we cant use more numbers than useLimit
13
// storing each use labels in map to count the use limit of that number
14
int i = 0;
15
while (i < numWanted) {
16
int t = q.top().first; // number
17
int ind = q.top().second; // labels index
18
q.pop();
19
if (m[labels[ind]] < useLimit) // if less than count then include in our answer
20
{
21
ans += t;
22
m[labels[ind]]++;
23
i++;
24
}
25
if (q.size() == 0) {
26
break;
27
}
28
}
29
return ans;
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0