Fill The Truck Maximum Units on a Truck Solution Amazon OA 2021

Fill The Truck Maximum Units on a Truck Solution

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.
  • numberOfUnitsPerBoxiis 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.

Also See: Amazon OA Online Assessment 2021 Questions and Answers

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

Example 1:

Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output: 8
Explanation: There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.

Example 2:

Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
Output: 91

Constraints:

  • 1 <= boxTypes.length <= 1000
  • 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000
  • 1 <= truckSize <= 106

Solution

Simple Sort Solution

For this problem, we simply need to prioritize the more valuable boxes first. To do this, we should sort the boxtypes array (B) in descending order by the number of units per box (B[i][1]).

Then we can iterate through B and at each step, we should add as many of the boxes as we can, until we reach the truck size (T). We should add the number of boxes added multiplied by the units per box to our answer (ans), and decrease T by the same number of boxes.

Once the truck is full (T == 0), or once the iteration is done, we should return ans.

  • Time Complexity: O(N log N) where N is the length of B, for the sort
  • Space Complexity: O(1)

Program C++:

class Solution {
public:
    int maximumUnits(vector<vector<int>>& B, int T) {
        sort(B.begin(), B.end(), [](auto& a, auto& b) { return b[1] < a[1];});
        int ans = 0;
        for (auto& b : B) {
            int count = min(b[0], T);
            ans += count * b[1], T -= count;
			if (!T) return ans;
        }
        return ans;
    }
};

Program Python:

class Solution:
    def maximumUnits(self, B: List[List[int]], T: int) -> int:
        B.sort(key=lambda x: x[1], reverse=True)
        ans = 0
        for b,n in B:
            boxes = min(b, T)
            ans += boxes * n
            T -= boxes
            if T == 0: return ans
        return ans

Program Java:

class Solution {
    public int maximumUnits(int[][] B, int T) {
        Arrays.sort(B, (a,b) -> b[1] - a[1]);
        int ans = 0;
        for (int[] b : B) {
            int count = Math.min(b[0], T);
            ans += count * b[1];
            T -= count;
			if (T == 0) return ans;
        }
        return ans;
    }
}

Program JavaScript:

var maximumUnits = function(B, T) {
    B.sort((a,b) => b[1] - a[1])
    let ans = 0
    for (let i = 0; T && i < B.length; i++) {
        let count = Math.min(B[i][0], T)
        ans += count * B[i][1], T -= count
    }
    return ans
};

Greedily Select Max Units/Box Ratio

The given constraints for numberOfUnitsPerBox are small enough that we can use an approach similar to counting sort to reduce the time complexity to O(N).

Here, we can declare an array freq of size=1000 (which is maximum number of units per box) where freq[i] will denote the number of boxes that can hold i number of units. We can iterate through the given boxTypes array and populate the freq array. Then we can iterate over the freq array and greedily choose starting from i=1000 till we run out of truckSize or pick all available boxes.

Time Complexity : O(N)
Space Complexity : O(1)

Program C++:

int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
	int freq[1001]{0}, maxUnits = 0;   // freq[i] = number of boxes that can hold i units
	for(auto& box : boxTypes) freq[box[1]] += box[0];
	// greedily choose starting from max units till either truckSize runs out or you choose all boxes
	for(int units = 1000; truckSize > 0 && ~units; --units) { 
		maxUnits += min(truckSize, freq[units]) * units;
		truckSize -= freq[units];
	}
	return maxUnits;
}

Program Python:

def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
    freq, max_units = [0]*1001, 0
    for box in boxTypes:
        freq[box[1]] += box[0]
    for units in range(1000,0,-1):
        if truckSize < 0: break
        max_units += min(truckSize, freq[units]) * units
        truckSize -= freq[units]
    return max_units

Program Java:

class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        Arrays.sort(boxTypes,(a,b)->(b[1]-a[1]));
        
        int i=0;
        int ans=0;
        while(i<boxTypes.length && truckSize>0){
            if(truckSize-boxTypes[i][0]>=0){
                truckSize-=boxTypes[i][0];
                ans+=boxTypes[i][0]*boxTypes[i][1];}else{
                ans+=boxTypes[i][1]*truckSize;
                truckSize=0;
        }
            System.out.println(ans);
            i++;
        }
        return ans;
    }
}

Bucket Sort Solution

This time we will store info into sizeBucket, an array of 1001 elements (to cover all the provided range) all set to 0 and that we will populate while also storing the extremes of said range in minBucket and maxBucket, increasing each bucket of size boxType[1] by boxType[0] (how many we have) as we go. Be sure to add, not to assign here, since we do not know if we would be given multiple entries of the same size.

Once done, we can loop through the boxes we bucket-sorted going from maxBucket to minBucket (included) and following a logic specular to the previous one.

This bucket sorting version, which despite using buckets, turns out to be even more efficient in terms of space too:

Program C++:

class Solution {
public:
    int maximumUnits(vector<vector<int>>& boxes, int truckSize) {
        // support variables
        int res = 0, sizeBucket[1001] = {}, maxBucket = INT_MIN, minBucket = INT_MAX;
        // bucket sorting tthe boxes and recording the bucket range
        for (auto &boxType: boxes) {
            maxBucket = max(maxBucket, boxType[1]);
            minBucket = min(minBucket, boxType[1]);
            sizeBucket[boxType[1]] += boxType[0];
        }
		// carrying as many larger sized boxes as we can first
        for (int i = maxBucket, size, currBatch; i >= minBucket; i--) {
            size = sizeBucket[i];
            if (!size) continue;
            currBatch = min(size, truckSize);
            truckSize -= currBatch;
            res += currBatch * i;
            if (!truckSize) break;
        }
        return res;
    }
};

Also See: AMCAT Study Materials, Preparation Guide

Also See: Microsoft Online Assessment Questions and Solution

Amazon Online Assessment Test Questions:

2 thoughts on “Fill The Truck Maximum Units on a Truck Solution Amazon OA 2021”

  1. Hello, Neat post. There is a problem with your site in web explorer, would test
    this? IE still is the market chief and a big component of folks will leave out your
    magnificent writing because of this problem.

    Reply

Leave a Comment