Mark and Toys Discussions | Algorithms | HackerRank

Mark and Toys

Sort by

recency

|

1044 Discussions

|

  • + 0 comments

    Java

    	Collections.sort(prices);
            int sum = 0;
            int count = 0;
            for(Integer i : prices){
                sum += i;
                if(sum > k){
                    break;
                } else{
                    count++;
                }
            }
            return count;
    
  • + 0 comments
    def maximumToys(prices, k):
        # Write your code here
        prices.sort()
        current=0
        toys=0
        for toy in prices:
            if toy+current<=k:
                current+=toy 
                toys+=1
        return toys
    
  • + 0 comments

    Java:

    public static int maximumToys(List<Integer> prices, int k) {
        prices.sort(Comparator.naturalOrder());
        int i = 0;
        int totalSpend = 0;
        for (;i < prices.size() && totalSpend < k; ++i) {
            totalSpend += prices.get(i);
        }
        return i-1;
    }
    
  • + 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

    I've added a little optimisation to filter out elements above the budget, that we don't need spending time ordering.

    public static int maximumToys(List<Integer> prices, int k) {
            var sorted = prices.stream()
                               .filter(p -> p <= k)
                               .sorted()
                               .collect(Collectors.toList());
            
            var i = 0;
            var budget = k;
            
            while(i < sorted.size() && budget >= sorted.get(i)) {
                budget -= sorted.get(i);
                ++i;
            }
            
            return i;
        }