# x 213. House Robber II

[213. House Robber II](https://leetcode.com/problems/house-robber-ii/)\\

> time: O(N)

> space: O(1)

```javascript
/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function (nums) {
    if (nums.length === 1) return nums[0];
    if (nums.length < 3) return Math.max(nums[0], nums[1]);

    let answer = -Infinity;

    let first = Math.max(nums[0], 0);
    let second = Math.max(nums[1], first);

    for (let i = 2; i < nums.length - 1; i++) {
        const curr = nums[i];
        const temp = second;
        second = Math.max(second, first + curr);
        second = Math.max(second, curr);
        first = temp;
    }
    answer = Math.max(second, answer);

    first = 0
    second = Math.max(nums[1], first);
    for (let i = 2; i < nums.length; i++) {
        const curr = nums[i];
        const temp = second;
        second = Math.max(second, first + curr);
        second = Math.max(second, curr);
        first = temp;
    }
    answer = Math.max(second, answer);

    return answer;
};

```

> time: O(N)

> space: O(N)

```jsx
/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function(nums) {
    if (nums.length === 1) return nums[0];
    if (nums.length < 3) return Math.max(nums[0], nums[1]);
    
    let sums = new Array(nums.length).fill(0);
    sums[0] = Math.max(nums[0], 0);
    sums[1] = Math.max(nums[1], sums[0]);
    sums[2] = Math.max(nums[2] + sums[0], sums[1]);

    for (let i = 3; i < nums.length - 1; i++) {
        const curr = nums[i];
        sums[i] = Math.max(sums[i - 2] + curr, sums[i - 1]);
        sums[i] = Math.max(sums[i], curr);
    }
    const odd = sums[nums.length - 2];

    sums = new Array(nums.length).fill(0);
    sums[0] = 0
    sums[1] = Math.max(nums[1], 0);
    for (let i = 2; i < nums.length; i++) {
        const curr = nums[i];
        sums[i] = Math.max(sums[i - 2] + curr, sums[i - 1]);
        sums[i] = Math.max(sums[i], curr);
    }
    const even = sums[nums.length - 1];

    return Math.max(odd, even);
};

// 1 5 -2 1
// 3 5 3 1
// 1 2 3 4
// 4 3 2 1
// 10 1 1 1
// 1 1 1 10
// 1 10 1 1
// 1 1 10 1
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/dynamic-programming/x-213.-house-robber-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
