Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: A thief robs houses in a row but cannot rob two adjacent houses. Find the maximum loot.

Problem: A thief robs houses in a row but cannot rob two adjacent houses. Find the maximum loot.
def rob(a):
    take = skip = 0
    for x in a:
        take, skip = skip + x, max(take, skip)
    return max(take, skip)
print(rob([2, 7, 9, 3, 1]), rob([2, 1, 1, 2]))
What is printed?
  1. A. 12 4
  2. B. 11 4
  3. C. 12 3
  4. D. 10 4

Correct answer: A. 12 4

take = best ending by robbing this house, skip = best without it. [2, 7, 9, 3, 1] → 2 + 9 + 1 = 12. [2, 1, 1, 2] → rob both ends = 4; taking every other house from index 0 gives only 3. O(n), O(1).

More Coding Interview Problems questions

Exams that ask this topic