Mark and Toys Discussions | Algorithms | HackerRank

Mark and Toys

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