Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Fractional knapsack — take items (or fractions) by value/weight ratio to maximise value within capacity.
Problem: Fractional knapsack — take items (or fractions) by value/weight ratio to maximise value within capacity.
def frac(items, W):
total = 0.0
for v, w in sorted(items, key=lambda x: x[0] / x[1], reverse=True):
take = min(w, W); total += v * take / w; W -= take
if W == 0: break
return f"{total:.2f}"
print(frac([(60, 10), (100, 20), (120, 30), (40, 5)], 45))What is printed?- A. 220.00
- B. 260.00
- C. 240.00
- D. 180.00
Correct answer: C. 240.00
Ratios: 8 (40/5), 6 (60/10), 5 (100/20), 4 (120/30). Take items 4, 1 and 2 fully (weight 35, value 200) and 10 of the last item's 30 kg (value 120 × 10/30 = 40): 240.00. Unlike 0/1 knapsack, the greedy ratio order is optimal when items can be split.
More Coding Interview Problems questions
- Problem: One pass of Lomuto partition (pivot = last element) as used in quicksort. python def lomuto(a): p = a[-1]; i = -1 for j in…
- Problem: Count the swaps made by bubble sort and by selection sort on the same array. python def bubble(a): a = a[:]; s = 0 for i in…
- Problem: Bottom-up heapify (max-heap) of an array; print the resulting array. python def heapify(a): n = len(a) def down(i): while True…
- Problem: Insert keys into a hash table of size 7 with open addressing and LINEAR probing, h(k) = k mod 7. python T = [None] 7 for k in…
- Problem: Double hashing with h1(k) = k mod 11 and h2(k) = 7 − (k mod 7); probe i is (h1 + i·h2) mod 11. Print the slots probed for key 58…
- Problem: Exponential (galloping) search: double the bound until a[hi] ≥ target, then binary search in (hi/2, hi]. Count the comparisons of…