Program to find maximum units that can be put on a truck in Python

Suppose we have a set of boxes represented as a 2D array called boxTypes, where boxTypes[i] contains two elements [number of boxes of type i, number of units per box of type i]. Now we also have another value k, which is the maximum number of boxes that can be put on that truck. We can select any boxes to put on the truck as long as the number of boxes does not cross k. We have to find the maximum total number of units that can be put on the truck.

So, if the input is like boxTypes = [[2,4],[3,3],[4,2]], k = 6, then the output will be 19, because there are

• 2 boxes of type 1 and each contains 4 units

• 3 boxes of type 2 and each contains 3 units

• 4 boxes of type 3 and each contains 2 units

as k = 6, we can take all boxes of type 1 and 2, and only one box of type 3, so there will be (2*4) + (3*3) + 2 = 8 + 9 +2 = 19 items.

To solve this, we will follow these steps −

• sort boxTypes based on number of items present in each box

• total := 0, fill := 0

• for each i in boxTypes, do

• if fill + i[0] <= k, then

• fill := fill + i[0]

• total := total + i[0] * i[1]

• otherwise,

• total := total + (k - fill) * i[1]

• come out from loop

Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

def solve(boxTypes, k):
boxTypes.sort(key = lambda x : x[1], reverse = True)
total = 0
fill = 0
for i in boxTypes:
if fill + i[0] <= k:
fill += i[0]
total += i[0] * i[1]
else:
total += (k - fill) * i[1]
break

boxTypes = [[2,4],[3,3],[4,2]]
k = 6
print(solve(boxTypes, k))

Input

[[2,4],[3,3],[4,2]], 6

Output

19