Mark and Toys Discussions | Algorithms | HackerRank

Mark and Toys

Sort by

recency

|

1042 Discussions

|

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

    My Java solution with o(n log n) time complexity and o(1) space complexity:

    public static int maximumToys(List<Integer> prices, int k) {
            // sort array ascending
            Collections.sort(prices);
            
            // subtract price from k until k - price < 0
            int maxToys = 0;
            int i = 0;
            while(k - prices.get(i) >= 0){
                maxToys++;
                k -= prices.get(i);
                i++;
            }
            return maxToys;
        }
    
  • + 0 comments
    def maximumToys(prices, k):
        prices.sort()
        for i in range(len(prices)+1):
            if(sum(prices[0:i])<k):
                pass
            elif(sum(prices[0:i])>k):
                return i-1
            elif(sum(prices[0:i])==k):
                return i