-
Notifications
You must be signed in to change notification settings - Fork 1
/
14 January Maximum Number of Toys
51 lines (50 loc) · 1.25 KB
/
14 January Maximum Number of Toys
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution{
public:
vector<int> maximumToys(int N,vector<int> A,int Q,vector<vector<int>> Queries){
// code here
vector<int> ans(Q);
vector<long long> prefix(N);
vector<pair<int, int>> arr(N);
for (int i = 0; i < N; i++)
{
arr[i] = {A[i], i};
}
sort(arr.begin(), arr.end());
unordered_map<int, int> mp;
for (int i = 0; i < N; i++)
{
mp[arr[i].second] = i;
}
long long sum = 0;
for (int i = 0; i < N; i++)
{
sum += arr[i].first;
prefix[i] = sum;
}
for (int m = 0; m < Q; m++)
{
int money = Queries[m][0];
int k = Queries[m][1];
int idx = upper_bound(prefix.begin(), prefix.end(), money) - prefix.begin();
vector<int> v(k);
for (int i = 0; i < k; i++)
{
v[i] = mp[Queries[m][i + 2] - 1];
}
sort(v.begin(), v.end());
int count = 0, j;
for (int i = 0; i < k; i++)
{
j = v[i];
if (j < idx)
{
count++;
money += arr[j].first;
idx = upper_bound(prefix.begin(), prefix.end(), money) - prefix.begin();
}
}
ans[m] = idx - count;
}
return ans;
}
};