Skip to content
The Computer Science
TheCScience
  • Engineering Subjects
    • Human Values
    • Computer System Architecture
    • Microprocessor
    • Digital Communication
    • Internet of Things
  • NCERT Solutions
    • Class 12
    • Class 11
  • Solutions
    • HackerRank
      • C Solutions
      • C++ Solutions
      • Java Solutions
      • Python Solutions
      • Algorithms Solutions
      • Data Structures Solutions
    • HackerEarth Solutions
    • Leetcode Solutions
  • JEE 2027
The Computer Science
TheCScience

HackerRank Mark and Toys Problem Solution

Yashwant Parihar, June 5, 2023August 1, 2024

In this post, we will solve HackerRank Mark and Toys Problem Solution.

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
prices [1, 2, 3, 4]
k = 7
The budget is 7 units of currency. He can buy items that cost [1, 2, 3] for 6. or [3, 4] for 7 units. The maximum is 3 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, n and k, the number of priced toys and the amount Mark has to spend.
The next line contains n space-separated integers prices[i]

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].

HackerRank Mark and Toys Problem Solution
HackerRank Mark and Toys Problem Solution

Table of Contents

  • Mark and Toys C Solution
  • Mark and Toys C++ Solution
  • Mark and Toys C Sharp Solution
  • Mark and Toys Java Solution
  • Mark and Toys JavaScript Solution
  • Mark and Toys Python Solution

Mark and Toys C Solution

#include<stdio.h>

void mergeSort(float arr[],int low,int mid,int high);
void partition(float arr[],int low,int high);

int main()
{
    register int i=0,j=0,count=0;
    int items;
    float money,total=0,small;
    scanf("%d %f",&items,&money);
    float cost[100004];
    for(i=0;i<items;i++)
        scanf("%f",cost+i);
  /*  for(i=0;i<items-1;i++)
        for(j=0;j<items-1;j++)
    {
        small=cost[j];
        if(small>=cost[j+1])
        {
            cost[j]=cost[j+1];
            cost[j+1]=small;
        }
    }*/
    partition(cost,0,items-1);
    i=0;
    while(total<=money)
    {
        total=total+cost[i];
        count++;
        i++;
    }
    printf("%d",count-1);
    return 0;
}

 void partition(float arr[],int low,int high){

    int mid;

    if(low<high){
         mid=(low+high)/2;
         partition(arr,low,mid);
         partition(arr,mid+1,high);
         mergeSort(arr,low,mid,high);
    }
}

void mergeSort(float arr[],int low,int mid,int high){

    int i,m,k,l,temp[100004];

    l=low;
    i=low;
    m=mid+1;

    while((l<=mid)&&(m<=high)){

         if(arr[l]<=arr[m]){
             temp[i]=arr[l];
             l++;
         }
         else{
             temp[i]=arr[m];
             m++;
         }
         i++;
    }

    if(l>mid){
         for(k=m;k<=high;k++){
             temp[i]=arr[k];
             i++;
         }
    }
    else{
         for(k=l;k<=mid;k++){
             temp[i]=arr[k];
             i++;
         }
    }

    for(k=low;k<=high;k++){
         arr[k]=temp[k];
    }
}

Mark and Toys C++ Solution

#include <bits/stdc++.h>

using namespace std;

typedef long long int ll;
typedef pair<int,int> pi;

const int MAX = 1e5+7;

vector<ll> v;

int main() {
    int n;
    ll x,sum,k;
    cin>>n>>k;
    for(int i=0;i<n;i++){
        cin>>x;
        v.push_back(x);
    }
    sort(v.begin(),v.end());
    sum=0;
    int i;
    for(i=0;i<n;i++){
       sum+=v[i];
        if(sum>k) break;
    }
    cout<<i;
    
   
    return 0;
}

Mark and Toys C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
         string[] arr = Console.ReadLine().Split();
            int N = Int32.Parse( arr[0]);
            int K = Int32.Parse(arr[1]);
            int count = 0, i;
            string[] arr1 = Console.ReadLine().Split();
            
            int[] a = new int[N];
            for ( i = 0; i < N; i++)
            {
                a[i] = Int32.Parse(arr1[i]);
            }


            Array.Sort(a);
            
            for (i = 0; i < a.Length; i++)
            {
                count += Convert.ToInt32(a[i]);
                if (count>K)
                {
                    break;
                }
            }
            Console.WriteLine(i);
         
    }
}

Mark and Toys Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'maximumToys' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. INTEGER_ARRAY prices
     *  2. INTEGER k
     */

    public static int maximumToys(List<Integer> prices, int k) {
    // Write your code here
        Collections.sort(prices);
        int maxToys = 0;
        
        for (int i=0; i<prices.size() && prices.get(i) <= k; i++){
            if (prices.get(i) <= k){
                maxToys++;
                k = k - prices.get(i);
            }
        }
         
        return maxToys;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int n = Integer.parseInt(firstMultipleInput[0]);

        int k = Integer.parseInt(firstMultipleInput[1]);

        List<Integer> prices = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        int result = Result.maximumToys(prices, k);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Mark and Toys JavaScript Solution

function processData(input) {
    //Enter your code here
    var data = input.split("\n");
    var data2 = data[0].split(" ");
    var n = parseInt(data2[0]);
    var k = parseInt(data2[1]);
    var toys = data[1].split(" ").sort(function(a, b){return a-b});
    var total = 0;
    var toysCnt = 0;
    for(var i = 0; i < toys.length; i++)
    {          
        total+=parseInt(toys[i]);
        if(total <= k)
        {    
            toysCnt++;     
        }else
            break;
    }
    process.stdout.write(toysCnt+"\n");        
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Mark and Toys Python Solution


import string

line1 = input()#"7 50"
line2 = input()#"1 12 5 111 200 1000 10"

#print(line1);
#print(line2);

itemNum = int(line1.split()[0])
totalMoney = int(line1.split()[1])

money_string_array = line2.split()
money_set = set()
money = []
for each in (money_string_array):
	#money_set.add(int(each))
	money.append(int(each))

#money = list(money_set)
money.sort()

sum_money = 0
sum_toy = 0
for each in money:
	if sum_money + each <= totalMoney :
		sum_toy += 1
		sum_money += each
	else:
		break;

#print(itemNum + totalMoney)
#print(money);
print(sum_toy)
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post

Engineering Core Subjects

Digital Communication Subject
Internet of Things Subject
Computer Architecture subject
Human Value Subject

JEE Study Materials

JEE Physics Notes
JEE Chemistry Notes

TheCScience

At TheCScience.com, our mission is to make quality education accessible to everyone. We provide in-depth, easy-to-understand articles covering Secondary, Senior Secondary, and Graduation-level subjects.

Our content is designed to simplify complex concepts through clear explanations, diagrams, and structured learning—helping students build strong fundamentals and succeed academically without financial barriers.

Pages

About US

Contact US

Privacy Policy

DMCA

Our Tools

Hosting - get 20% off

Engineering Subjects

Internet of Things

Human Values

Digital Communication

Computer System Architecture

Microprocessor

Programming Tutorials

Data Structure and Algorithm

C

Java

NCERT

Class 12th

©2026 TheCScience | WordPress Theme by SuperbThemes