joshita / dev

Published

- 2 min read

Maximum number of units in a truck

img of Maximum number of units in a truck

Maximum number of units in 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.

Return the maximum total number of units that can be put on the truck.

  1. Approach, we need to maximise the total units we should put in the truck, for that we need to sort by total units
  2. At each step we need to calculate the remaining space in the truk as we place the units
  3. Finally if the space becomes less than the units we can accomodate we should add the leftover units only
  4. Important part is to break when we add only the remaining capacity so that we dont move fwd in the array.
   private int totalUnitsAdded (int [][] boxes) {
     int truckSize = 4;
     int remainingSize = 0;
     int answer = 0;

     for (int i =0; i < boxes.length; i++) {
        remainingSize = truckSize - boxes[i][0];
        if(remainingSize < boxes[i][0]) {
            if(remainingSize > 0) {
                answer += (Math.abs(remainingSize) * boxes[i][1]);
                break; // good point there can be n number of boxes remaining, we just need to fill the box
            } 
        } else {
            answer += (boxes[i][0] * boxes[i][1]);
        }
     }
        return answer;
    }