Mark and Toys Discussions | Algorithms | HackerRank

Mark and Toys

Sort by

recency

|

1049 Discussions

|

  • + 0 comments

    My current implementation uses the condition if (k - item > 0) This condition prevents purchasing an item when the remaining budget becomes exactly zero after the purchase. However, according to the problem statement, the goal is to maximize the number of toys that can be purchased without exceeding the budget. There is no restriction that the remaining budget must stay positive. Reaching exactly zero should be considered valid, since: The total cost does not exceed the budget. if (k - item > 0) means the algorithm only allows purchases when some money remains after buying the toy This incorrectly excludes valid scenarios where: k - item == 0 for example : prices = [1, 2, 3, 4] k = 6 The algorithm stops early and returns 2 instead of 3 This is not a valid logical restriction according to the problem definition. The condition should be updated to: if (k - item >= 0) The test cases should also ensure that scenarios where the budget becomes exactly zero are included, since these are valid and expected outcomes. public static int maximumToys(List prices, int k) { List SortedPrices = prices.OrderBy(x=>x).ToList(); int cnt = 0; foreach(var item in SortedPrices) { if(k-item>0) { cnt++; k-=item; } else { break; } } return cnt; }

    }

    The budget is fully utilized.

    No constraint in the problem forbids spending the entire amount.

  • + 0 comments

    It seems thisproblem is not about sorting and it's more about having greedy thinking! So using a built-in sort apparently is acceptable!

  • + 0 comments

    Simple Java Solution:

    public static int maximumToys(List<Integer> prices, int k) {
        prices = prices.stream().sorted().collect(Collectors.toList());
        int count = 0;
        int sum = 0;
        for(int i=0;i<prices.size();i++){
            sum = sum + prices.get(i);
            if(sum <= k){
                count++;
            }
            else {
                break;
            }
        }
        return count;
        }
    
  • + 0 comments

    JS

    function maximumToys(prices, limit) {
        let spent = 0;
        return prices.sort((a, b) => +a - +b).findIndex(price => {
            if ((spent += price) > limit) {
                return true;
            }
        });
    }
    
  • + 0 comments
    int maximumToys(vector<int> prices, int k) {
        sort(prices.begin(), prices.end(), greater<int>());
        int count = 0;
        
        while (k>0) {
            k-=prices.back();
            prices.pop_back();
            count++;
        }
        
        return count-1;
    }