Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://practice.geeksforgeeks.org/contest/gfg-weekly-coding-contest-91/problems/#
- John, owns an inherited jewellery. Since his family is in need of money, he decides to sell that jewellery, but he is unaware at what price he should sell it. So he consulted his N friends and each friend guessed a range [low, high] which can be the price of that diamond according to that friend. John is confused but these guessed ranges. But decides that the price that is suggested by atleast k friends might be the best price to sell at.
- John goes to the market and quotes his sell price range [l,r]. John quotes Q queries where each query is a price range quoted by John. Return the number of "best prices" that exist in this range quoted by John.
- BEST PRICE is a price that is suggested by atleast K friends.
- Example 1:
- Input :
- n=2
- price={{1,3},{2,4}}
- k=2
- q=1
- queries={{1,4}}
- Output:
- {2}
- Explanation:
- As price 2 and 3 is suggested by both
- the friends. 2 and 3 are suggested by 2 friends and since 2>=k, both of these prices are best price.
- So 2 and 3 is best price.
- Example 2:
- Input :
- n=3
- price={{1,3},{3,5},{2,6}}
- k=3
- q=2
- queries={{1,3},{5,6}}
- Output:
- {1,0}
- Explanation:
- For query 1 [1,3], price 3 is the only suggested price by atleast k friends. So answer is 1 best price
- For query 2 [5,6], there is no best price.
- ------------------------------------------------------------------------------------------------------------------------------------
- class Solution {
- public:
- int mx=0;
- vector<int> LINE_SWEEP(vector<vector<int>> &price, vector<vector<int>> &queries){
- vector<int> freq(mx+10,0);
- for(auto p: price){
- freq[p[0]]++;
- freq[p[1]+1]--;
- }
- for(int i=1;i<mx+10;i++){
- freq[i]=freq[i]+freq[i-1];
- }
- return freq;
- }
- vector<int> bestPrice(int n, vector<vector<int>> price, int k, int q, vector<vector<int>> queries) {
- // line sweep algorithm
- for(auto p: price){
- mx=max(mx,p[1]);
- }
- for(auto q: queries){
- mx=max(mx,q[1]);
- }
- vector<int> freq=LINE_SWEEP(price,queries);
- int best[mx+10]={0};
- for(int i=1;i<mx+10;i++){ // calculate the number of elements having >=k
- if(freq[i]>=k){
- best[i]=1;
- }
- best[i]+=best[i-1];
- }
- vector<int> res;
- for(auto q: queries){
- int answer=best[q[1]]-best[q[0]-1];
- res.push_back(answer);
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment