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.

Problem Understanding

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 units.

Algorithm

To solve this, we will follow these steps −

  • Sort boxTypes based on units per box in descending order (greedy approach)

  • Initialize total = 0 and fill = 0

  • For each box type, take as many boxes as possible without exceeding k

  • Return the total units

Implementation

Let us see the following implementation to get better understanding −

def solve(boxTypes, k):
    # Sort by units per box in descending order (greedy approach)
    boxTypes.sort(key=lambda x: x[1], reverse=True)
    
    total = 0
    fill = 0
    
    for i in boxTypes:
        if fill + i[0] <= k:
            # Take all boxes of this type
            fill += i[0]
            total += i[0] * i[1]
        else:
            # Take only remaining boxes that fit
            total += (k - fill) * i[1]
            break
    
    return total

# Test the function
boxTypes = [[2,4],[3,3],[4,2]]
k = 6
result = solve(boxTypes, k)
print(f"Maximum units: {result}")
Maximum units: 19

How It Works

The algorithm uses a greedy approach

  1. Sort by efficiency: We sort boxes by units per box in descending order to prioritize high-value boxes

  2. Fill greedily: We take as many boxes as possible from each type, starting with the most valuable

  3. Handle remainder: When we can't fit all boxes of a type, we take only what fits

Example with Step-by-Step Execution

def solve_with_steps(boxTypes, k):
    print(f"Original boxTypes: {boxTypes}")
    
    # Sort by units per box (descending)
    boxTypes.sort(key=lambda x: x[1], reverse=True)
    print(f"Sorted boxTypes: {boxTypes}")
    
    total = 0
    fill = 0
    
    for i, box_type in enumerate(boxTypes):
        boxes_count, units_per_box = box_type
        print(f"\nStep {i+1}: Processing {boxes_count} boxes with {units_per_box} units each")
        
        if fill + boxes_count <= k:
            fill += boxes_count
            units_added = boxes_count * units_per_box
            total += units_added
            print(f"  Took all {boxes_count} boxes, added {units_added} units")
        else:
            remaining_capacity = k - fill
            units_added = remaining_capacity * units_per_box
            total += units_added
            print(f"  Took only {remaining_capacity} boxes, added {units_added} units")
            break
        
        print(f"  Total boxes used: {fill}, Total units: {total}")
    
    return total

# Test with detailed output
boxTypes = [[2,4],[3,3],[4,2]]
k = 6
result = solve_with_steps(boxTypes, k)
print(f"\nFinal result: {result} units")
Original boxTypes: [[2, 4], [3, 3], [4, 2]]
Sorted boxTypes: [[2, 4], [3, 3], [4, 2]]

Step 1: Processing 2 boxes with 4 units each
  Took all 2 boxes, added 8 units
  Total boxes used: 2, Total units: 8

Step 2: Processing 3 boxes with 3 units each
  Took all 3 boxes, added 9 units
  Total boxes used: 5, Total units: 17

Step 3: Processing 4 boxes with 2 units each
  Took only 1 boxes, added 2 units

Final result: 19 units

Conclusion

This greedy algorithm efficiently maximizes truck capacity by prioritizing boxes with higher units per box. The time complexity is O(n log n) due to sorting, and it guarantees the optimal solution for this truck loading problem.

Updated on: 2026-03-25T20:31:57+05:30

774 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements