Mark and Toys : HackerRank Problem Solution

Mark and Jane are very happy after having their first kid. Their son is very fond of toys, so Mark wants to buy some. There are  different toys lying in front of him, tagged with their prices, but he has only . He wants to maximize the number of toys he buys with this money.

Now, you are Mark's best friend and have to help him buy as many toys as possible.




Input Format 
The first line contains two integers,  and , followed by a line containing  space separated integers indicating the products' prices.

Output Format 

An integer that denotes maximum number of toys Mark can buy for his son.

Constraints 
A toy can't be bought multiple times.

Sample Input

7 50
1 12 5 111 200 1000 10

Sample Output

4

Explanation

He can buy only 4 toys at most. These toys have the following prices: 1,12,5,10

C++ Implementation:


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;

struct compare
    {
    bool operator()(const int& l,const int&r)
        {
        return l>r;
    }
};

int main() 
{
    long long n,k,x,answer=0,count=0;
    priority_queue <int,vector<int>,compare> pq;
    cin>>n>>k;
    for(int i=0;i<n;i++)
        {
        cin>>x;
        pq.push(x);
    }
    answer += pq.top();
    pq.pop();
    while(!pq.empty() && answer<=k)
        {
        answer += pq.top();
        pq.pop();
        count++;
    }
    cout<<count<<endl;
    return 0;
}