Mark and Toys Discussions | Algorithms | HackerRank

Mark and Toys

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