Mark and Toy HackerRank Problem solution

Problem:

Mark and Jane are very happy after having their first child. Their son loves toys, so Mark wants to buy some. There are a number of different toys lying in front of him, tagged with their prices. Mark has only a certain amount to spend, and he wants to maximize the number of toys he buys with this money. Given a list of toy prices and an amount to spend, determine the maximum number of gifts he can buy.

Note Each toy can be purchased only once.

Example

The budget is  units of currency. He can buy items that cost  for , or  for  units. The maximum is  items.

Function Description

Complete the function maximumToys in the editor below.

maximumToys has the following parameter(s):

  • int prices[n]: the toy prices
  • int k: Mark’s budget

Returns

  • int: the maximum number of toys

Input Format

The first line contains two integers,  and, the number of priced toys and the amount Mark has to spend.
The next line contains  space-separated integers 

Sample Input

7 50
1 12 5 111 200 1000 10

Sample Output

4

Explanation

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

Solution:

int maximumToys(vector<int> prices, int k) {
    sort(prices.begin(), prices.end());
    int n = prices.size();
    int res = 0;
    int count = 0;
    for(int i=0;i<n;i++){
        if(res+prices[i]<=k){
            res += prices[i];
            count++;
        }
    }
    return count;
}

I hope you understand the concept and code and if not then don’t hesitate to contact me comment down below or send your query on my telegram.
you can also check my other solution.

Two sum problem leetcode solution:

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart