Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: 2n people must be split so n fly to city A and n to city B; costs[i] = [costA, costB]. Minimise total cost (sort by costA − costB).

Problem: 2n people must be split so n fly to city A and n to city B; costs[i] = [costA, costB]. Minimise total cost (sort by costA − costB).
def two_city(c):
    c.sort(key=lambda x: x[0] - x[1]); n = len(c) // 2
    return sum(x[0] for x in c[:n]) + sum(x[1] for x in c[n:])
print(two_city([[40, 100], [300, 50], [60, 70], [500, 480], [80, 20], [90, 95]]))
What is printed?
  1. A. 740
  2. B. 620
  3. C. 655
  4. D. 710

Correct answer: A. 740

Differences A − B: −60, 250, −10, 20, 60, −5. The three most negative (−60, −10, −5) go to A: 40 + 60 + 90 = 190; the rest go to B: 480 + 20 + 50 = 550. Total 190 + 550 = 740. Sending each person to their cheaper city ignores the n/n constraint.

More Coding Interview Problems questions

Exams that ask this topic