Data Structures & AlgorithmsHardInfosys · Accenture pattern

Houses in a row hold [3, 2, 7, 10, 1, 9]. No two ADJACENT houses may both be chosen. What is the maximum total? (dp[i] = max(dp[i − 1], dp[i − 2] + a[i]).)

  1. A. 19
  2. B. 20
  3. C. 21
  4. D. 22

Correct answer: D. 22

dp: 3, 3, 10, 13, 13, 22. Best set: 3 + 10 + 9 = 22 (houses 1, 4, 6). Taking every other house from the start (3 + 7 + 1 = 11) is far worse, and 3 + 7 + 9 = 19 misses that choosing 10 (and giving up its neighbour 7) pays more.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic