Bird
Raised Fist0
Interview Prepgreedy-algorithmseasyAmazonGoogle

Maximum Units on a Truck

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
📋
Problem

Imagine you are a truck driver who needs to maximize the number of units loaded onto your truck from different box types, each with a limited number of boxes and units per box.

You are assigned to put some number of boxes onto a truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxes_i, numberOfUnitsPerBox_i]: - numberOfBoxes_i is the number of boxes of type i. - numberOfUnitsPerBox_i 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. Return the maximum total number of units that can be put on the truck.

1 ≤ boxTypes.length ≤ 10^51 ≤ numberOfBoxes_i, numberOfUnitsPerBox_i ≤ 10^51 ≤ truckSize ≤ 10^9
Edge cases: truckSize is zero → output 0Only one box type with boxes less than truckSize → output all units from that typeMultiple box types with same units per box → pick any order but total units same
</>
IDE
def maximumUnits(boxTypes: list[list[int]], truckSize: int) -> int:public int maximumUnits(int[][] boxTypes, int truckSize)int maximumUnits(vector<vector<int>>& boxTypes, int truckSize)function maximumUnits(boxTypes, truckSize)
def maximumUnits(boxTypes, truckSize):
    # Write your solution here
    pass
class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
    // Write your solution here
    return 0;
}
function maximumUnits(boxTypes, truckSize) {
    // Write your solution here
}
0/9
Common Bugs to Avoid
Wrong: 0Not handling empty input or zero truckSize correctly, returning zero always.Add condition to return 0 only when truckSize is zero or boxTypes is empty, otherwise proceed.
Wrong: sum of all units without sortingNot sorting boxTypes by units per box descending, picking boxes in input order.Sort boxTypes by units per box descending before picking boxes greedily.
Wrong: units assuming unlimited boxesTreating problem as unbounded knapsack, ignoring box count limits.Limit boxes picked to min(numberOfBoxes, remaining truckSize) for each box type.
Wrong: incorrect units due to off-by-one in truckSize decrementLoop or decrement logic off by one, picking wrong number of boxes.Ensure truckSize decrements correctly after picking boxes and loop conditions are accurate.
Wrong: TLE or timeoutUsing brute force exponential approach instead of sorting + greedy.Implement sorting by units descending and greedy picking to achieve O(n log n) complexity.
Test Cases
t1_01basic
Input{"boxTypes":[[1,3],[2,2],[3,1]],"truckSize":4}
Expected8

Pick 1 box of type 0 (3 units) and 2 boxes of type 1 (2 units each) and 1 box of type 2 (1 unit). Total units = 3 + 4 + 1 = 8.

t1_02basic
Input{"boxTypes":[[5,10],[2,5],[4,7]],"truckSize":6}
Expected57

Pick 5 boxes of type 0 (10 units each) and 1 box of type 2 (7 units). Total units = 50 + 7 = 57.

t2_01edge
Input{"boxTypes":[],"truckSize":0}
Expected0

No boxes and truck size zero means no units can be loaded.

t2_02edge
Input{"boxTypes":[[3,5]],"truckSize":5}
Expected15

Only one box type with 3 boxes, truckSize 5 allows all 3 boxes to be loaded for total 15 units.

t2_03edge
Input{"boxTypes":[[2,4],[3,4],[1,4]],"truckSize":4}
Expected16

All box types have same units per box (4). Pick any 4 boxes total for 16 units.

t3_01corner
Input{"boxTypes":[[5,10],[5,1]],"truckSize":5}
Expected50

Greedy trap: picking boxes in input order yields 5*10 + 0 = 50 units, correct. But if code picks low units first, total is 5 units only.

t3_02corner
Input{"boxTypes":[[3,5],[2,10]],"truckSize":4}
Expected30

Confusion between 0/1 and unbounded: must pick boxes up to truckSize, not unlimited. Pick 2 boxes of 10 units and 2 boxes of 5 units = 20 + 10 = 30 units.

t3_03corner
Input{"boxTypes":[[1,100],[1,1]],"truckSize":1}
Expected100

Off-by-one error: truckSize 1 means only one box can be picked. Must pick box with 100 units, not 1 unit.

t4_01performance
Input{"boxTypes":[[100000,100000],[99999,99999],[99998,99998],[99997,99997],[99996,99996],[99995,99995],[99994,99994],[99993,99993],[99992,99992],[99991,99991],[99990,99990],[99989,99989],[99988,99988],[99987,99987],[99986,99986],[99985,99985],[99984,99984],[99983,99983],[99982,99982],[99981,99981],[99980,99980],[99979,99979],[99978,99978],[99977,99977],[99976,99976],[99975,99975],[99974,99974],[99973,99973],[99972,99972],[99971,99971],[99970,99970],[99969,99969],[99968,99968],[99967,99967],[99966,99966],[99965,99965],[99964,99964],[99963,99963],[99962,99962],[99961,99961],[99960,99960],[99959,99959],[99958,99958],[99957,99957],[99956,99956],[99955,99955],[99954,99954],[99953,99953],[99952,99952],[99951,99951],[99950,99950],[99949,99949],[99948,99948],[99947,99947],[99946,99946],[99945,99945],[99944,99944],[99943,99943],[99942,99942],[99941,99941],[99940,99940],[99939,99939],[99938,99938],[99937,99937],[99936,99936],[99935,99935],[99934,99934],[99933,99933],[99932,99932],[99931,99931],[99930,99930],[99929,99929],[99928,99928],[99927,99927],[99926,99926],[99925,99925],[99924,99924],[99923,99923],[99922,99922],[99921,99921],[99920,99920],[99919,99919],[99918,99918],[99917,99917],[99916,99916],[99915,99915],[99914,99914],[99913,99913],[99912,99912],[99911,99911],[99910,99910],[99909,99909],[99908,99908],[99907,99907],[99906,99906],[99905,99905],[99904,99904],[99903,99903],[99902,99902],[99901,99901],[99900,99900],[99899,99899],[99898,99898],[99897,99897],[99896,99896],[99895,99895],[99894,99894],[99893,99893],[99892,99892],[99891,99891],[99890,99890],[99889,99889],[99888,99888],[99887,99887],[99886,99886],[99885,99885],[99884,99884],[99883,99883],[99882,99882],[99881,99881],[99880,99880],[99879,99879],[99878,99878],[99877,99877],[99876,99876],[99875,99875],[99874,99874],[99873,99873],[99872,99872],[99871,99871],[99870,99870],[99869,99869],[99868,99868],[99867,99867],[99866,99866],[99865,99865],[99864,99864],[99863,99863],[99862,99862],[99861,99861],[99860,99860],[99859,99859],[99858,99858],[99857,99857],[99856,99856],[99855,99855],[99854,99854],[99853,99853],[99852,99852],[99851,99851],[99850,99850],[99849,99849],[99848,99848],[99847,99847],[99846,99846],[99845,99845],[99844,99844],[99843,99843],[99842,99842],[99841,99841],[99840,99840],[99839,99839],[99838,99838],[99837,99837],[99836,99836],[99835,99835],[99834,99834],[99833,99833],[99832,99832],[99831,99831],[99830,99830],[99829,99829],[99828,99828],[99827,99827],[99826,99826],[99825,99825],[99824,99824],[99823,99823],[99822,99822],[99821,99821],[99820,99820],[99819,99819],[99818,99818],[99817,99817],[99816,99816],[99815,99815],[99814,99814],[99813,99813],[99812,99812],[99811,99811],[99810,99810],[99809,99809],[99808,99808],[99807,99807],[99806,99806],[99805,99805],[99804,99804],[99803,99803],[99802,99802],[99801,99801],[99800,99800]],"truckSize":1000000000}
⏱ Performance - must finish in 2000ms

Large input with n=100 and large truckSize to test O(n log n) sorting + greedy approach within 2 seconds.

Practice

(1/5)
1. You are given a list of non-negative integers and need to arrange them to form the largest possible number when concatenated. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Dynamic Programming to find the maximum concatenation by exploring all subsequences
B. Sorting the numbers as strings using a custom comparator that compares concatenations
C. Greedy approach by always picking the largest integer first
D. Brute force generating all permutations and selecting the maximum concatenation

Solution

  1. Step 1: Understand the problem requires ordering numbers to maximize concatenation

    The key is to compare pairs by concatenating in both possible orders and deciding which order yields a larger combined string.
  2. Step 2: Recognize that sorting with a custom comparator based on concatenation comparisons guarantees optimal order

    This approach ensures the final concatenation is lexicographically largest, unlike greedy or DP which do not handle pairwise ordering correctly.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Custom comparator sorting is the standard solution for this problem [OK]
Hint: Compare concatenations as strings to decide order [OK]
Common Mistakes:
  • Assuming greedy pick of largest integer works
  • Using DP which is unnecessary
  • Brute force is correct but inefficient
2. You are given a positive integer n. The task is to find the largest integer less than or equal to n such that its digits are in non-decreasing order from left to right. Which algorithmic approach guarantees an optimal solution efficiently?
easy
A. Divide and conquer splitting the number into halves and solving recursively
B. Dynamic Programming that tries all digit combinations to build the largest monotone number
C. Brute force decrementing from n downwards checking monotonicity for each number
D. Greedy algorithm scanning digits from right to left, adjusting digits and setting trailing digits to 9

Solution

  1. Step 1: Understand the problem constraints

    The problem requires the largest number ≤ n with digits in non-decreasing order, which suggests a digit-wise adjustment rather than enumerating all numbers.
  2. Step 2: Identify the approach that efficiently fixes digits from right to left

    The greedy right-to-left scan decreases digits when a violation is found and sets subsequent digits to 9, ensuring the largest monotone number ≤ n.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Greedy right-to-left fix is optimal and efficient [OK]
Hint: Greedy right-to-left digit fix ensures optimal monotone number [OK]
Common Mistakes:
  • Thinking brute force is efficient enough
  • Assuming DP is needed for digit monotonicity
  • Believing divide and conquer applies here
3. Consider the following Python code snippet implementing the optimal solution to remove k digits from a number string to get the smallest number. What is the output of removeKdigits("1432", 2)?
def removeKdigits(num: str, k: int) -> str:
    builder = []
    for digit in num:
        while k > 0 and builder and builder[-1] > digit:
            builder.pop()
            k -= 1
        builder.append(digit)
    while k > 0:
        builder.pop()
        k -= 1
    result = ''.join(builder).lstrip('0')
    return result if result else '0'
easy
A. "14"
B. "13"
C. "12"
D. "32"

Solution

  1. Step 1: Trace builder and k during iteration

    Start with builder = [], k=2 - digit='1': builder=['1'], k=2 - digit='4': '4' > '1', append: builder=['1','4'], k=2 - digit='3': '3' < '4', pop '4', k=1; append '3': builder=['1','3'] - digit='2': '2' < '3', pop '3', k=0; append '2': builder=['1','2']
  2. Step 2: Remove remaining k and finalize

    k=0, no more pops. Result = '12' after stripping leading zeros.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Output matches expected smallest number after removing 2 digits [OK]
Hint: Pop larger digits when smaller digit found until k=0 [OK]
Common Mistakes:
  • Not popping enough digits when smaller digit appears
  • Removing digits from front only
  • Forgetting to strip leading zeros
4. Examine the following BFS-based code for Jump Game II. Which line contains a subtle bug that can cause incorrect jump counts or infinite loops?
medium
A. Line checking if next_pos == n - 1 to return jumps
B. Line incrementing jumps before processing current level
C. Line calculating furthest_jump without bounding by n-1
D. Line adding next_pos to visited set

Solution

  1. Step 1: Identify furthest_jump calculation

    furthest_jump = pos + nums[pos] can exceed array bounds, causing range() to go out of range or runtime error.
  2. Step 2: Check impact

    Without min(pos + nums[pos], n - 1), code may attempt invalid indices, causing incorrect behavior or crashes.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Bounding furthest_jump by n-1 prevents out-of-range errors [OK]
Hint: Always bound jump indices within array length [OK]
Common Mistakes:
  • Forgetting to limit furthest_jump to n-1
  • Incrementing jumps incorrectly
  • Missing visited set usage
5. What is the time complexity of the optimal min-heap based algorithm for finding the minimum number of platforms required for n trains?
medium
A. O(n²) due to nested loops checking all train pairs
B. O(n) because each train is processed once
C. O(n log n) due to sorting and heap operations for each train
D. O(n log k) where k is the maximum number of platforms needed

Solution

  1. Step 1: Identify sorting cost

    Sorting n trains by arrival time costs O(n log n).
  2. Step 2: Analyze heap operations

    Each train causes at most one push and one pop on the heap, each O(log n), so total O(n log n).
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Sorting + heap operations dominate complexity [OK]
Hint: Sorting + heap push/pop per train -> O(n log n) [OK]
Common Mistakes:
  • Assuming O(n) ignoring sorting and heap costs
  • Confusing heap size k with n for complexity
  • Mistaking nested loops for optimal approach complexity