Data Structures & AlgorithmsModerateWipro · Accenture pattern
What is printed? (greedy fractional knapsack)
What is printed? (greedy fractional knapsack)
items = [(10, 60), (20, 100), (30, 120)] # (weight, value)
cap, total = 50, 0.0
for w, v in sorted(items, key=lambda x: x[1] / x[0], reverse=True):
take = min(w, cap); total += v * take / w; cap -= take
if cap == 0: break
print(total)- A. 240.0
- B. 220.0
- C. 160.0
- D. 180.0
Correct answer: A. 240.0
Taking items by value per kg (6, 5, 4) and splitting the last one: 60 + 100 + (20/30)·120 = 240. Greedy is optimal when fractions are allowed; for 0/1 items the best is only 220. O(n log n).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (minimum platforms / overlapping intervals with a heap) python import heapq iv = sorted([(1, 4), (2, 3), (3, 6), (5, 7)…
- A complete binary tree is stored in an array with the root at index 1. A node at index 37 – what are its parent, left child and right…
- What is printed? (Catalan-style recursion with memo: number of ways to fully parenthesise a product of n matrices) python from functools…
- Union–find with union by rank and full path compression. What is printed? python p = list(range(8)); rank = [0] 8 def find(x): if p[x] !=…
- 0-1 BFS on a grid: stepping into '#' costs 1 (a wall to break), stepping onto '.' or 'T' costs 0. What is the minimum number of walls to…
- How many topological orders does this DAG on 6 vertices have? (counted by DP over bitmasks of already-placed vertices) python from…