Lesson 2 · Unit 02
House robber
Take it or skip it: a choice at every cell
What you practise
- Take or skip
Try a question from this lesson
Pick one
Houses in a row hold [2, 7, 9, 3, 1]. You may not rob two neighbouring houses. What is the most you can take?
Correct answer
12
Why
Houses 1, 3 and 5 give 2 + 9 + 1 = 12. The two richest houses, 7 and 9, are neighbours, so 16 is out. 7 + 3 = 10 and 2 + 9 = 11 are both legal but leave money behind.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Take it or skip it
Let dp[i] be the most money from the first i houses. Look at the last of those houses and decide.
Skip it: you keep dp[i - 1]. Take it: its neighbour is off limits, so you add its money to dp[i - 2]. The cell is the larger of the two.
def rob(cash):
n = len(cash)
dp = [0] * (n + 1)
dp[1] = cash[0]
for i in range(2, n + 1):
take = dp[i - 2] + cash[i - 1]
dp[i] = max(dp[i - 1], take)
return dp[n]function rob(cash) {
const n = cash.length;
const dp = Array(n + 1).fill(0);
dp[1] = cash[0];
for (let i = 2; i <= n; i++) {
const take = dp[i - 2] + cash[i - 1];
dp[i] = Math.max(dp[i - 1], take);
}
return dp[n];
}function rob(cash: number[]): number {
const n = cash.length;
const dp = Array<number>(n + 1).fill(0);
dp[1] = cash[0];
for (let i = 2; i <= n; i++) {
const take = dp[i - 2] + cash[i - 1];
dp[i] = Math.max(dp[i - 1], take);
}
return dp[n];
}Python notedp has n + 1 cells because cell i covers the first i houses, so house i is cash[i - 1].
TypeScript notecash: number[] is an array of numbers. Array<number>(n + 1) gives dp the same type; without it, fill(0) returns any[].
10 more exercises in the app
- 3× multiple choice
- 3× type the answer
- 2× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.