Mark and Toys Discussions | Algorithms | HackerRank

Mark and Toys

Sort by

recency

|

1037 Discussions

|

  • + 0 comments

    Here is my c++ solution, you also have a vidéo explanation here : https://youtu.be/DFQO52aB-qI

    int maximumToys(vector<int> prices, int k) {
        sort(prices.begin(), prices.end());
        int i = 0;
        while(i < prices.size() && k >= prices[i]){
            k -= prices[i];
            i++;
        }
        return i;
    }
    
  • + 0 comments
    public static int maximumToys(List < Integer > prices, int k) {
        // Sort the prices in ascending order
        Collections.sort(prices);
    
        // Use reduce to calculate the count
        int[] counter = prices.stream() //
            // .sorted() //
            .reduce(new int[] {0, k}, (arr, price) - > {
                if (arr[1] >= price) {
                    // Deduct the price from the budget
                    arr[1] -= price;
                    // Increment the count
                    arr[0]++;
                }
    
                return arr;
            }, (a, b) - > a);
    
        // Extract the count from the accumulator
        return counter[0];
    }
    
  • + 0 comments

    Recursive solution in python:

    def maximumToys(prices, k):
        sys.setrecursionlimit(10**6) #Avoid recursion error
        def rec_function(ac,k,toys,sorted_prices,i):
            if ac <= k:    
                price = sorted_prices[i+1]
                return rec_function(ac+price,k,toys+1,sorted_prices,i+1)
            return toys
        sorted_prices = sorted(prices)
        ac = sorted_prices[0]
        toys = 0
        return rec_function(ac,k,toys,sorted_prices,0)
        
    
  • + 0 comments

    Java

    public static int maximumToys(List prices, int k) {

    Collections.sort(prices);

    int totalPrice = 0; int numToBuy = 0;

    while(totalPrice <= k){

    totalPrice = totalPrice + prices.get(numToBuy);
    
    numToBuy++;
    

    } //subtracting 1 since while loop will run one additional time when the value should not be added before ending return numToBuy-1;

  • + 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;
    }