Mark and Toys Discussions | Algorithms | HackerRank

Mark and Toys

Sort by

recency

|

1033 Discussions

|

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

    Using c#

    public static int maximumToys(List<int> prices, int k)
    {
      int n = prices.Count;
      int toyCount = 0;
      int totalSpent = 0;
    
      prices.Sort();
    
      // Buy toys while the budget allows
      for (int i = 0; i < n; i++)
      {
        if (totalSpent + prices[i] <= k)
        {
          totalSpent += prices[i];
          toyCount++;
        }
        else
        {
          // If we can't afford this toy, stop the process
          break;
        }
      }
    }
    
  • + 0 comments

    Java Solution

    public static int maximumToys(List prices, int k) { // Write your code here Collections.sort(prices); int toys=0; /for(int i=0;i/

        int i=0;
        while(prices.get(i)<k && i<prices.size()){
            k=k-prices.get(i);
            toys=toys+1;
            i++;
        }
        return toys;
    
    }
    
  • + 0 comments

    Straigthforward python solution:

    def maximumToys(prices, k):

    sorted_prices = sorted(prices)
    cost = 0    
    
    for i in range(len(prices)):
        cost += sorted_prices[i]
        if cost > k:
            return i
    
  • + 0 comments

    PHP

    function maximumToys($prices, $k) {
        // Write your code here
        sort ($prices);
        $hasil   = 0;
        $counter = 0;
        
        for ($i=0; $i < count($prices); $i++) {
            if (($hasil+$prices[$i]) <= $k) {
                $hasil+=$prices[$i];
                $counter++;
            }
            else {
                break;
            }
        }
        return $counter;
    }