Data Structures & AlgorithmsHardCodeforces Div2 C/D · Amazon SDE OA
A rod of length 8 can be cut into integer pieces, and a piece of length L sells for p[L] with p = [1, 5, 8, 9, 10, 17, 17, 20] for L = 1..8. Find the maximum total revenue by DP over the first piece cut.
A rod of length 8 can be cut into integer pieces, and a piece of length L sells for p[L] with p = [1, 5, 8, 9, 10, 17, 17, 20] for L = 1..8. Find the maximum total revenue by DP over the first piece cut.
p=[0,1,5,8,9,10,17,17,20]
n=8
best=[0]*(n+1)
for x in range(1,n+1):
best[x]=max([p[l]+best[x-l] for l in range(1,x+1)])
print(best[n])What is printed?- A. 20
- B. 21
- C. 22
- D. 18
Correct answer: C. 22
Rod cutting DP: the best value for length x is the max over the first piece length l of p[l] plus the best for the rest. Restricting pieces to length four or less loses the 8-long combinations, taking only the single best price ignores combinations, and excluding the full-length piece drops the option of not cutting.
More Coding Interview Problems questions
- Array b = [1, 11, 2, 10, 4, 5, 2, 1]. Find the length of its longest bitonic subsequence: a subsequence that strictly increases and then…
- Count the 4-element subsets of {1, 2, ..., 12} whose sum is divisible by 5. Count by brute force over combinations. python from itertools…
- Find the smallest positive integer x such that x ≡ 2 (mod 3), x ≡ 3 (mod 5) and x ≡ 2 (mod 7). Solve by brute-force search. python…
- How many trailing zeros does 100! have in base 10? Use Legendre's formula with powers of 5, counted by running the loop over p = 5, 25…
- The string s = "abcbdab" needs characters deleted to become a palindrome. What is the minimum number of deletions? Use n minus the longest…
- A 4×4 grid has rows "..#.", ".##.", "##.#", "#...". Entering a cell costs 1 if it is '#' and 0 otherwise, and you may move in four…