Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
What is printed? (rod cutting – maximise revenue)
What is printed? (rod cutting – maximise revenue)
price = [0, 1, 5, 8, 9, 10, 17, 17, 20]
n = 8; r = [0] * (n + 1)
for j in range(1, n + 1):
r[j] = max(price[i] + r[j - i] for i in range(1, j + 1))
print(r[4], r[8])- A. 9 20
- B. 10 20
- C. 10 24
- D. 10 22
Correct answer: D. 10 22
r[j] = max over the first piece i of price[i] + r[j − i]. Length 4: 2 + 2 → 5 + 5 = 10 beats a single 4 (9). Length 8: 2 + 6 → 5 + 17 = 22 beats an uncut rod (20). This is an unbounded knapsack, O(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? (subset sum with a boolean DP table) python a = [3, 34, 4, 12, 5, 2] def can(t): dp = [True] + [False] t for x in a: for…
- What is printed? (egg dropping: minimum trials in the worst case) python def trials(eggs, floors): # dp[m] = max floors checkable with m…
- What is printed? (0/1 knapsack with item reconstruction) python w = [1, 3, 4, 5]; v = [1, 4, 5, 7]; W = 7; n = 4 dp = [[0] (W + 1) for in…
- What is printed? (number of BSTs vs number of binary heaps on keys 1..4) python from math import comb from functools import lrucache…
- What is printed? (diameter of an unweighted tree with two BFS passes) python from collections import deque edges = [(1, 2), (1, 3), (2…
- What is printed? (articulation points by brute force removal) python edges = [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 5), (5, 3), (5…