HackerRank — Mark and Toys solution in Java

Problem Description

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

Constraints

A toy can’t be bought multiple times.

Sample Input

Sample Output

Explanation

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

My Approach

The key point of this problem is that we need to determine the “maximum number of toys” he can buy. We don’t need to maximize his expenditure or even spend the full amount, we only need to ensure the number of toys bought is the maximum. That means we need to take a greedy approach by choosing the least expensive toy at first and work our way above.

This is my attempted solution:

Explanation

So, I start by sorting my array. This makes sure that I look at the toys starting from their lowest price. Then I loop through the sorted prices, checking if the current price of the toy is cheaper than my running budget, k. If it is, I subtract that amount from k a.k.a my current available budget and increment max by 1. If k is less than the current price of the toy, we know for sure that there’s no toy we can afford anymore since my array is already sorted in ascending order. Hence, we break on the else-statement and return max.

Final Comments

This was a very easy problem, which took me less than 15 minutes to pass all the test cases. Hope this helps. Please feel free to comment if you find a solution with greater optimization, preferably one that does not require the sorting of the array. Thanks.

Software Engineer at Headstorm