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?- A. 740
- B. 620
- C. 655
- 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
- Problem: Can the cards be split into groups of W consecutive values? python from collections import Counter def straights(hand, W): if…
- Problem: Report the median of every window of size k (sorted-list version with bisect). python from bisect import insort, bisectleft def…
- Problem: A single-threaded CPU receives tasks [enqueueTime, processingTime]. When idle it runs the available task with the shortest…
- Problem: A min-stack supports push, pop, top and getMin in O(1) by storing (value, current minimum) pairs. python st, out = [], [] def…
- Problem: Josephus problem: n people in a circle, every k-th person is eliminated; find the 1-based position of the survivor. python def…
- Problem: Count permutations of 1..n where, for every position i (1-based), the value is divisible by i or i is divisible by the value…