Sort by

recency

|

2421 Discussions

|

  • + 0 comments
        """
        An optimized version. Instead of checking all combinations, we sort both lists in descending order
        and break the inner loop when b - total cannot improve."""
    		
    def getMoneySpent(keyboards, drives, b):
        keyboards.sort(reverse = True)
        drives.sort(reverse = True)
        max_spent = -1
        diff = b 
        for k in keyboards:
            for d in drives:
                total = k + d
                if b - total >= 0:
                    if b - total < diff:
                        diff = b - total
                        max_spent = total
                    else :
                        break
        return max_spent
    
  • + 0 comments
    from itertools import product
    def get_money_spent(keyboards, drives, b):
        possible_sums = [ x + y for x,y in list(product(keyboards, drives)) if x + y <= b ]
        return max(possible_sums) if len(possible_sums) > 0 else -1
    
  • + 1 comment
    def getMoneySpent(b, keyboards, drives):
        # 
        # Write your code here.
        final = []
        for i in keyboards:
            for j in drives:
                if (i+j) <= b:
                    final.append(i+j)
                    
        if len(final) == 0:
            return -1
        else:
            return max(final)
    
  • + 0 comments

    Two-pointer solution:

        keyboards.sort()
        drives.sort(reverse=True)
        
        best = -1
        i = j = 0
        
        while i < len(keyboards) and j < len(drives):
            total = keyboards[i] + drives[j]
            if total > b:
                j += 1
            else:
                if total > best:
                    best = total
                i += 1
        return best
    
  • + 0 comments

    C# static int getMoneySpent(int[] keyboards, int[] drives, int b) { int max = -1; Array.Sort(keyboards); Array.Sort(drives);

     int i = 0;
     int j = drives.Length - 1;
    
     while (i <= keyboards.Length - 1 && j >= 0)
     {
         int sum = keyboards[i] + drives[j];
    
         if (sum > b)
         {
             j--;
         }
         else
         {
             i++;
    
             if (sum > max)
             {
                 max = sum;
             }
         }
     }
    
     return max;
    

    }