[LeetCode] Most Beautiful Item for Each Query

2070. Most Beautiful Item for Each Query

You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively.

You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0.

Return an array answer of the same length as queries where answer[j] is the answer to the jth query.

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
class Solution {
public:
vector<int> maximumBeauty(vector<vector<int>>& A, vector<int>& B) {
vector<pair<int,int>> Q;
int n = A.size(), m = B.size();
vector<int> res(m);
for(int i = 0; i < m; i++) {
Q.push_back({B[i], i});
}
sort(begin(Q), end(Q));
sort(begin(A), end(A));
vector<pair<int, int>> pmax {{0,0}};
int ma = 0, p = 0;
while(p < n) {
int price = A[p][0];
while(p < n and A[p][0] == price) {
ma = max(ma, A[p++][1]);
}
pmax.push_back({price, ma});
}
p = 0;
for(int i = 0; i < m; i++) {
auto [req, idx] = Q[i];
while(p + 1 < pmax.size() and pmax[p + 1].first <= req) p++;
if(pmax[p].first <= req) res[idx] = pmax[p].second;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/05/PS/LeetCode/most-beautiful-item-for-each-query/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.