↻one more pass.
Dynamic programming · Medium

House Robber: the idea to remember.

Maximize the sum of nonnegative house values without choosing adjacent houses.

Solve on LeetCode ↗

The core insight

At each house, compare skipping it with taking it plus the best result before its neighbor.

Why it works

An optimal prefix either excludes the last house or includes it and must exclude the previous house.

The mistake to avoid

Keep the old two-back value until the take case has been computed.

Time: O(n)Space: O(1)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int rob(int[] nums) {
    int twoBack = 0, oneBack = 0;
    for (int value : nums) {
        int best = Math.max(oneBack, twoBack + value);
        twoBack = oneBack;
        oneBack = best;
    }
    return oneBack;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.