Data Structures & AlgorithmsModerateTCS NQT · Infosys
Which statement about the 'house robber' DP on a line is correct?
- A. It must be solved with bitmask DP because adjacency constraints are not monotone
- B. dp[i] = max(dp[i−1], dp[i−2] + a[i]) runs in O(n) time and O(1) extra space
- C. It needs O(n²) time, because every pair of houses must be compared
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A greedy solution to a scheduling problem sorts jobs by profit and places each into the latest free slot before its deadline. What must…
- A coin-change problem uses coins {1, 3, 4} and asks for the minimum number of coins for each amount. Which statement is correct?
- In the circular array [1, 2, 1], what is the next greater element of the element at index 2 (search continues around the circle, -1 if no…
- Looking from the right, a building is seen if it is strictly taller than every building to its right (the rightmost is always seen). How…
- A list holds 1 to 10. Every node whose 1-based position is a multiple of 3 is deleted. What is the sum of the remaining values?
- How many unordered index pairs i < j in [2, 3, 4, 5, 6] have a[i] + a[j] prime?