I knew this was a DP problem pretty fast but fumbled explaining the recurrence out loud.
Start by clarifying the problem and edge cases, then propose a dynamic programming solution where dp[i] represents the maximum sum up to house i. Explain the recurrence dp[i] = max(dp[i-1], dp[i-2] + nums[i]) and optimize space to O(1) by keeping only two variables.
Pro tip: After presenting the optimal solution, briefly mention how you would test it with edge cases like empty array, single house, and all positive/negative values, and discuss potential follow-ups like returning the actual houses selected.
Restate the problem in your own words and ask clarifying questions about input constraints, empty arrays, negative numbers, and whether the array can be modified.
Mention that a brute force approach would consider all subsets without consecutive elements, which is exponential, and thus we need a more efficient method.
Define dp[i] as the max sum up to index i. Explain that for each house, you either skip it (dp[i-1]) or take it plus the max sum up to i-2 (dp[i-2] + nums[i]), so dp[i] = max(dp[i-1], dp[i-2] + nums[i]).
Show how to reduce space from O(n) to O(1) by keeping only two variables (prevMax and currMax) and update them iteratively. Write clean code with meaningful variable names.
Walk through the example, test edge cases (empty, single element, all negatives), and state time complexity O(n) and space complexity O(1).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.