Mark and Toys Discussions | Algorithms | HackerRank

Mark and Toys

  • + 0 comments

    Java:

    public static int maximumToys(List<Integer> prices, int k) {
        // Sort the toy prices in ascending order
        Collections.sort(prices);
        
        int maximumToys = 0;
    
        // Iterate through the sorted prices
        for (int price : prices) {
            if (k >= price) { // Check if the current toy can be bought within the budget
                maximumToys++;
                k -= price; // Deduct the price of the toy from the budget
            } else {
                break; // Stop when the budget is insufficient for the next toy
            }
        }
    
        return maximumToys;
    }