In this HackerRank Mark and Toys Interview preparation kit, you have Given a list of toy prices and an amount to spend, determine the maximum number of gifts he can buy.
Problem solution in Python programming.
#!/bin/python3 import math import os import random import re import sys # Complete the maximumToys function below. def maximumToys(prices, k): items = 0 prices.sort() for p in prices: if p <= k: items += 1 k -= p else: break return items if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nk = input().split() n = int(nk[0]) k = int(nk[1]) prices = list(map(int, input().rstrip().split())) result = maximumToys(prices, k) fptr.write(str(result) + 'n') fptr.close()
Problem solution in Java Programming.
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int numItems = in.nextInt(); int cash = in.nextInt(); int[] items = new int[numItems]; for (int i = 0; i < numItems; i++) { items[i] = in.nextInt(); } System.out.println(findNumItemsPurchase(items, cash)); } public static int findNumItemsPurchase(int[] items, int cash) { Arrays.sort(items); int count = 0; for (int i = 0; i < items.length; i++) { if (cash - items[i] > 0) { cash -= items[i]; count += 1; } else { break; } } return count; } }
Problem solution in C++ programming.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { long long n, k; cin >> n >> k; vector<int> prices; for(int i = 0; i < n; i++) { int p; cin >> p; prices.push_back(p); } sort(prices.begin(), prices.end()); int t = 0; for(vector<int>::iterator it = prices.begin(); it != prices.end(); it++) { if(*it <= k) { t++; k -= *it; } else break; } cout << t << endl; return 0; }
Problem solution in C programming.
#include<stdio.h> void quicksort(int x[100000],int first,int last){ int pivot,j,temp,i; if(first<last){ pivot=first; i=first; j=last; while(i<j){ while(x[i]<=x[pivot]&&i<last) i++; while(x[j]>x[pivot]) j--; if(i<j){ temp=x[i]; x[i]=x[j]; x[j]=temp; } } temp=x[pivot]; x[pivot]=x[j]; x[j]=temp; quicksort(x,first,j-1); quicksort(x,j+1,last); }} int main() { int n,k,i,avail=0,count=0; scanf("%d",&n); scanf("%d",&k); int cost[n]; for(i=0;i<n;i++) scanf("%d",&cost[i]); quicksort(cost,0,n-1); while(avail<=k) { avail+=cost[count]; count++; } printf("%dn",count-1); return 0; }
Problem solution in JavaScript programming.
var data = ''; var run = function () { var parts = data.split('n'), totals = parts[0].split(' '), numToys = +totals[0], money = +totals[1], toyPrices = parts[1].split(' ').sort(function (a, b) { return a - b; }), total = 0, i = 0; while (total < money) { total += +toyPrices[i++]; } console.log(--i); } process.stdin.resume(); process.stdin.setEncoding('ascii'); process.stdin.on('data', function (input) { data += input; }); process.stdin.on('end', run);