ProgrammingHardCAT · MBA placement
A truck carries at most 10 boxes. The box types are given as (units per box, number of boxes): (5, 3), (4, 2), (3, 4), (2, 5). The greedy below takes boxes with the most units per box first, as many as fit. What is the total number of units loaded (printed)?
A truck carries at most 10 boxes. The box types are given as (units per box, number of boxes): (5, 3), (4, 2), (3, 4), (2, 5). The greedy below takes boxes with the most units per box first, as many as fit. What is the total number of units loaded (printed)?
sort types by units descending; slots = 10; total = 0
for each (u, c) in order
take t = min(c, slots) boxes; total = total + t * u; slots = slots - t
end for
Print total- A. 45
- B. 26
- C. 37
- D. 34
Correct answer: C. 37
Taking the 5-unit boxes fills 3 slots (15 units), the 4-unit boxes fill 2 (8 units), the 3-unit boxes fill 4 (12 units), and one 2-unit box fills the last slot, for 37. Ignoring the slot count gives 45, sorting ascending gives 26, and multiplying by the box count gives 34.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The greedy below repeatedly increases the smallest element of the array [3, 1, 2] by 1, three times in total. What is the minimum value of…
- For the function gcd(a, b) written by the procedure below, what is printed for gcd(252, 105)? (The procedure uses repeated remainder…
- The Fibonacci numbers F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2) satisfy gcd(F(m), F(n)) = F(gcd(m, n)). The procedure below uses this…
- The procedure below computes the last digit of 7^100 by starting from d = 1 and multiplying by 7, keeping only the last digit, once for…
- The number of ways to write 20 as p + q with p and q prime and p <= q is counted by the procedure below, which tries p = 2 to 10 and sets…
- For n = 1 to 100, the procedure below counts how many n satisfy that nn ends with the digit 1. What is printed? count = 0 for n = 1 to 100…