Writing greedy first was a mistake, and I think I knew it even as I was doing it.
Start by clarifying the problem constraints and edge cases, then explain that a greedy approach fails because local optimal choices don't guarantee global optimum. Implement the DP solution with O(n) time and O(1) space, and discuss trade-offs between greedy and DP.
Pro tip: Demonstrate maturity by acknowledging that greedy is incorrect for this problem, but discuss scenarios where greedy would work (e.g., if houses were in a line with no adjacency constraint). This shows you understand algorithm selection beyond just coding.
Restate the problem: given an array of non-negative integers representing money in each house, find the maximum amount you can rob without robbing adjacent houses. Confirm edge cases like empty array, single house, two houses.
Explain that a greedy strategy (e.g., always rob the house with the most money) doesn't work because it may prevent robbing two moderately valuable houses. Provide a counterexample to illustrate.
Define dp[i] as the maximum amount robbable from the first i houses. Recurrence: dp[i] = max(dp[i-1], dp[i-2] + nums[i-1]). Explain base cases.
Code the DP solution using two variables to track dp[i-1] and dp[i-2], achieving O(n) time and O(1) space. Walk through an example.
Compare greedy vs DP: greedy is simpler but incorrect; DP is optimal but requires more thought. Mention that DP can be extended to circular houses or other variations.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.