House robber

Pick values from a row so that no two picks are next to each other, and the total is as large as possible.

Time O(n)Space O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

best(i) is the best total using the first i houses. For each house there are two choices: skip it and keep best(i-1), or take it and add its value to best(i-2). Only those two values are read, so two variables are enough.

Code

public static int Rob(int[] a) {
    int prev2 = 0, prev1 = 0;
    foreach (int x in a) {
        int cur = Math.Max(prev1, prev2 + x);
        prev2 = prev1; prev1 = cur;
    }
    return prev1;
}
static int rob(int[] a) {
    int prev2 = 0, prev1 = 0;
    for (int x : a) {
        int cur = Math.max(prev1, prev2 + x);
        prev2 = prev1; prev1 = cur;
    }
    return prev1;
}
int rob(const vector<int>& a) {
    int prev2 = 0, prev1 = 0;
    for (int x : a) {
        int cur = max(prev1, prev2 + x);
        prev2 = prev1; prev1 = cur;
    }
    return prev1;
}
def rob(a: list[int]) -> int:
    prev2, prev1 = 0, 0
    for x in a:
        cur = max(prev1, prev2 + x)
        prev2, prev1 = prev1, cur
    return prev1

Tips

In the .NET library

Math.Max makes the take-or-skip choice one expression; the loop body is the whole algorithm.