ProgrammingVery hardAmazon OA · Goldman Sachs OA
What will be the output of the following pseudocode?
What will be the output of the following pseudocode?
Integer wt[3] = {2, 3, 4}, val[3] = {3, 5, 6}
Integer best[0..6] = all 0
for (each i from 0 to 2)
for (each w from wt[i] to 6)
if (best[w - wt[i]] + val[i] > best[w])
best[w] = best[w - wt[i]] + val[i]
end if
end for
end for
Print best[6]- A. 9
- B. 14
- C. 8
- D. 10
Correct answer: D. 10
Because w goes upward, best[w − wt[i]] may already include item i, so items can be reused: this is the unbounded knapsack. Two items of weight 3 give 5 + 5 = 10. The 0/1 answer 9 (weights 2 + 4) needs w to run downward.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? Integer lcm = 18, steps = 0 Integer a = 12, b = 18 while (lcm mod a != 0 OR lcm mod b…
- What will be the output of the following pseudocode? Integer total = 0 Procedure p(Integer n) if (n <= 0) return end if total = total + n…
- What will be the output of the following pseudocode? Integer c = 0 for (each i from 1 to 8) for (each j from i + 1 to 9) for (each k from…
- What will be the output of the following pseudocode? Function f(Integer a, Integer b) return a b - (a + b) End Function Print f(f(2, 3)…
- What will be the output of the following pseudocode? (Strings are indexed from 0) Integer calls = 0 Function pal(String s, Integer i…
- What will be the output of the following pseudocode? Integer s = 0, i = 0 while (i < 10) i = i + 1 if (i mod 3 == 0) continue end if s = s…