Maximum Units on a Truck

You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:
  • numberOfBoxesi is the number of boxes of type i.
  • numberOfUnitsPerBoxi is the number of units in each box of the type i.
You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.

Example 1:

Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output: 8

Approach

Java


import java.util.Arrays;
import java.util.Comparator;

public class MaximumUnitsTruck {
    public static void main(String[] args) {
        int[][] boxTypes = { { 13 }, { 22 }, { 31 } };
        int truckSize = 4;
        System.out.println(maximumUnits(boxTypes, truckSize));
    }

    // function to find the maximum units
    // on the truck
    static int maximumUnits(int[][] boxTypesint truckSize) {
        // sort the boxtypes
        Arrays.sort(boxTypes, Comparator.comparingDouble(o -> o[1]));
        int ans = 0;
        for (int i = boxTypes.length - 1; i >= 0; i--) {

            // if truckSize is less than bixTypes
            // then update answer and break
            if (truckSize <= boxTypes[i][0]) {
                ans = ans + truckSize * boxTypes[i][1];
                break;
            }
            // else update answer and
            // decrease the trucksize
            else {
                ans = ans + boxTypes[i][0] * boxTypes[i][1];
                truckSize -= boxTypes[i][0];
            }
        }
        // return the final answer
        return ans;

    }
}

C++
#include <bits/stdc++.h>
using namespace std;

//compartor to sort the array 
//in which order we wnad to sort the array
static bool cmp(vector<inta,vector<intb)
{
        if(a[1]==b[1])
              return a[0]>b[0];
        return a[1]>b[1];
}

//function to find the maximum units 
//on the truck
int maximumUnits(vector<vector<int>>& boxTypesint truckSize)
{

    // sort the boxtypes
        sort(boxTypes.begin(),boxTypes.end(),cmp);
        int ans=0;
        for(int i=0;i<boxTypes.size();i++)
          {

              //if truckSize is less than bixTypes
              //then update answer and break
              if(truckSize<=boxTypes[i][0]
              {
                  ans=ans+truckSize*boxTypes[i][1];
                  break;
              }
            //else update answer and 
            //decrease the trucksize
             else
             {
                 ans=ans+boxTypes[i][0]*boxTypes[i][1];
                 truckSize-=boxTypes[i][0];
             }
          }
    //return the final answer
        return ans;
        
}
int main()
{
   vector<vector<int>> boxTypes ={{1,3},{2,2},{3,1}};
   int truckSize = 4;
   cout<<maximumUnits(boxTypes,truckSize);
   return 0;
}


No comments:

Post a Comment