← Expedia Interview InsightsSoftware Engineer
Recognize this as a dynamic programming problem where at each house you decide to rob it (and add the max from two houses back) or skip it (keeping the max from one house back). Define dp[i] as the maximum amount robbable from the first i houses, then derive the recurrence dp[i] = max(dp[i-1], dp[i-2] + nums[i]). Optimize space to O(1) by tracking only the last two values.
Pro tip: Start by clarifying edge cases (empty array, single house) and then walk through a small example like [2,7,9,3,1] to validate your recurrence before coding. This shows structured thinking and catches off-by-one errors early.
Confirm the problem constraints: non-negative integers, no two adjacent houses, return maximum sum. Ask about edge cases like empty input or single house.
Let dp[i] be the max money from first i houses. At house i, either skip it (dp[i-1]) or rob it (dp[i-2] + nums[i]). So dp[i] = max(dp[i-1], dp[i-2] + nums[i]).
Initialize dp[0] = 0, dp[1] = nums[0]. Iterate from i=2 to n, applying the recurrence. Return dp[n].
Since dp[i] depends only on dp[i-1] and dp[i-2], use two variables (prev2, prev1) to achieve O(1) space. Update them each iteration.
Walk through a sample array to verify. State time complexity O(n) and space O(1). Mention that this is optimal.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.