Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: A van with fixed capacity picks up and drops passengers; trip [n, from, to] carries n passengers from km 'from' to km 'to' (they leave at 'to'). Can it complete all trips? (difference array)

Problem: A van with fixed capacity picks up and drops passengers; trip [n, from, to] carries n passengers from km 'from' to km 'to' (they leave at 'to'). Can it complete all trips? (difference array)
def ok(trips, cap):
    d = [0] * 1001
    for n, a, b in trips:
        d[a] += n; d[b] -= n
    cur = 0
    for x in d:
        cur += x
        if cur > cap: return False
    return True
t = [[3, 2, 6], [2, 4, 9], [4, 7, 10]]
print(ok(t, 6), ok(t, 5))
What is printed?
  1. A. True True
  2. B. True False
  3. C. False False
  4. D. False True

Correct answer: B. True False

Load by km: 3 (km 2–3), 5 (km 4–5), 2 (km 6), 6 (km 7–8), 4 (km 9). The first group leaves at km 6, before the third group boards at 7, so the peak is 6: fine for capacity 6, too many for 5.

More Coding Interview Problems questions

Exams that ask this topic