Data Structures & AlgorithmsModerateTCS CodeVita · Microsoft SDE OA

Houses have values e = [2, 7, 9, 3, 1, 8, 4, 6] and a robber cannot take two adjacent houses. Find the maximum sum that can be taken, using the DP that keeps the best value with and without the last house.

Houses have values e = [2, 7, 9, 3, 1, 8, 4, 6] and a robber cannot take two adjacent houses. Find the maximum sum that can be taken, using the DP that keeps the best value with and without the last house.
e=[2,7,9,3,1,8,4,6]
take=skip=0
for x in e:
    take,skip=skip+x,max(take,skip)
print(max(take,skip))
What is printed?
  1. A. 16
  2. B. 40
  3. C. 30
  4. D. 25

Correct answer: D. 25

The DP keeps two states per house: best sum when the house is taken (then the previous is skipped) and best when it is not. Taking every house ignores adjacency, summing the largest four values ignores positions, and alternating houses gives a fixed pattern that is not optimal.

More Coding Interview Problems questions

Exams that ask this topic