Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: A cable of length n is cut into pieces; prices[k − 1] is the price of a piece of length k. Maximise revenue (unbounded knapsack).
Problem: A cable of length n is cut into pieces; prices[k − 1] is the price of a piece of length k. Maximise revenue (unbounded knapsack).
def rod(prices, n):
dp = [0] * (n + 1)
for length in range(1, n + 1):
dp[length] = max(prices[k - 1] + dp[length - k] for k in range(1, min(length, len(prices)) + 1))
return dp[n]
print(rod([2, 6, 7, 10], 6), rod([3, 5, 8, 9], 4))What is printed?- A. 16 12
- B. 18 12
- C. 17 12
- D. 18 9
Correct answer: B. 18 12
dp[L] = best over the length k of the first piece. Prices per unit: 2, 3, 2.33, 2.5 for the first cable, so three 2-pieces give 6 + 6 + 6 = 18 (4 + 2 gives 16). Second: four 1-pieces give 12, beating the whole cable (9) and 3 + 1 (11). O(n · m).
More Coding Interview Problems questions
- Problem: Count subsets of distinct-position items whose values sum exactly to the target (0/1 counting knapsack with a 1-D array iterated…
- Problem: Compare the longest common SUBSTRING (contiguous) with the longest common SUBSEQUENCE of two log fragments. python def lcsub(a…
- Problem: Find the length of the shortest string that contains both a and b as subsequences: |a| + |b| − LCS(a, b). python def lcs(a, b)…
- Problem: Count the ways to roll n dice with k faces each so that the faces sum to target (mod 10⁹ + 7). python def dice(n, k, target…
- Problem: Picking a value v earns v points but deletes every v − 1 and v + 1 from the array; repeat until empty. Maximise points (reduces…
- Problem: Make two strings equal by deleting characters; the cost is the sum of ASCII codes of deleted characters. Minimise it (a weighted…