Bird
Raised Fist0

Given the following code and input, what is the final output printed?

easy🧾 Code Trace Q12 of Q15
Greedy Algorithms - Maximum Units on a Truck
Given the following code and input, what is the final output printed?
def maximumUnits(boxTypes, truckSize):
    boxTypes.sort(key=lambda x: x[1], reverse=True)
    totalUnits = 0
    for boxes, units in boxTypes:
        if truckSize == 0:
            break
        take = min(boxes, truckSize)
        totalUnits += take * units
        truckSize -= take
    return totalUnits

boxTypes = [[1,3],[2,2],[3,1]]
truckSize = 4
print(maximumUnits(boxTypes, truckSize))
A7
B8
C9
D6
Step-by-Step Solution
Solution:
  1. Step 1: Sort boxTypes by units descending

    Sorted list: [[1,3],[2,2],[3,1]] (already sorted)
  2. Step 2: Iterate and pick boxes until truckSize=0

    Take 1 box with 3 units -> totalUnits=3, truckSize=3 left; take 2 boxes with 2 units -> totalUnits=3+4=7, truckSize=1 left; take 1 box with 1 unit -> totalUnits=7+1=8, truckSize=0 stop.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Sum matches manual calculation [OK]
Quick Trick: Sort by units descending and pick greedily [OK]
Common Mistakes:
MISTAKES
  • Off-by-one in take calculation
  • Not stopping when truckSize=0
  • Incorrect sorting order
Trap Explanation:
PITFALL
  • Candidates often forget to break early or miscalculate min(boxes, truckSize), leading to wrong totals.
Interviewer Note:
CONTEXT
  • Tests ability to trace code and understand greedy iteration details.
Master "Maximum Units on a Truck" in Greedy Algorithms

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Greedy Algorithms Quizzes