Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: A truck holds at most 8 boxes. Each box type is (count, units per box). Maximise the total units loaded.
Problem: A truck holds at most 8 boxes. Each box type is (count, units per box). Maximise the total units loaded.
def max_units(boxes, cap):
total = 0
for cnt, units in sorted(boxes, key=lambda b: -b[1]):
take = min(cnt, cap)
total += take * units; cap -= take
if cap == 0: break
return total
print(max_units([(2, 5), (4, 9), (3, 7), (5, 2)], 8))What is printed?- A. 57
- B. 76
- C. 60
- D. 62
Correct answer: D. 62
Every box occupies one slot, so take the boxes with most units first: 4 × 9 = 36, 3 × 7 = 21, then 1 of the 5-unit boxes = 5 → 62. Since all boxes have equal 'weight', this greedy is optimal (unlike general 0/1 knapsack). O(k log k) for k box types.
More Coding Interview Problems questions
- Problem: Reorder the letters of s so that letters listed in order appear in that order; letters not in order go last, keeping their…
- Problem: A sorted list of distinct positive IDs has gaps. Find the k-th positive integer missing from it in O(log n): before index i, a[i]…
- Problem: Find the minimum of a rotated sorted array that may contain DUPLICATES. python def findmin(a): lo, hi = 0, len(a) - 1 while lo <…
- Problem: Arrange non-negative integers so that their concatenation forms the largest number (returned as a string). Sort with the…
- Problem: A company sends 2n candidates to two interview centres, n to each; costs[i] = (cost at A, cost at B). Minimise the total cost by…
- Problem: Delete the fewest characters so that no two distinct letters have the same (non-zero) frequency. python from collections import…