Data Structures & AlgorithmsModerateTCS NQT · Infosys

Which statement about the 'house robber' DP on a line is correct?

  1. A. It must be solved with bitmask DP because adjacency constraints are not monotone
  2. B. dp[i] = max(dp[i−1], dp[i−2] + a[i]) runs in O(n) time and O(1) extra space
  3. C. It needs O(n²) time, because every pair of houses must be compared
  4. D. Greedy selection of the largest house value at each step is always optimal

Correct answer: B. dp[i] = max(dp[i−1], dp[i−2] + a[i]) runs in O(n) time and O(1) extra space

Two rolling variables suffice for the recurrence, so the time is O(n) and the extra space O(1). Greedy by largest value fails: it can pick a large house that blocks two good neighbours.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic