ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[6] = {5, 5, 10, 100, 10, 5}
Integer incl = 0, excl = 0, t
for (each i from 0 to 5)
    t = max(incl, excl)
    incl = excl + a[i]
    excl = t
end for
Print max(incl, excl)
  1. A. 135
  2. B. 110
  3. C. 115
  4. D. 105

Correct answer: B. 110

This DP finds the largest sum of elements with no two adjacent. The best choice is 5 + 100 + 5 = 110. Taking every other element from the start gives 5 + 10 + 10 = 25, and from the second element 5 + 100 + 5 = 110 as well.

More Pseudocode and Code Tracing questions

Exams that ask this topic