HackerRank Mark and Toys Solution Js

Hi, here my solution in Javascript code to this HackerRank 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 prices and an amount to spend, what is the maximum number of toys Mark can buy? For example, if prices=[1,2,3,4] and Mark has k=7 to spend, he can buy items [1, 2, 3] for 6 or [3,4] for 7 units of currency. He would choose the first group of 3 items.

Solution:

// Complete the maximumToys function below.
function maximumToys(prices, k) {
    // sorting the array by price low to high
    let sortedPrices = prices.sort((a,b) => a - b);

    // to save the number of toys
    let counter = 0;

    // To go to every element of the prices array
    sortedPrices.forEach(price => {

        // comparing if my $ is greather than every element of the array (price)
        if (k > price) { // if true
            // then decrement my money $
            k = k - price;
            // counter increments means another toy
            counter++;
        }
    });

    // returning the number of toys that I can buy
    return counter;
}

maximumToys([1,12,5,111,200,1000,10], 750);

Result:

By Cristina Rojas.