# 198. House Robber

### Leetcode

<https://leetcode.com/problems/house-robber/description/>

### 題目

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array `nums` representing the amount of money of each house, return *the maximum amount of money you can rob tonight without alerting the police*.

&#x20;

**Example 1:**

<pre><code><strong>Input: nums = [1,2,3,1]
</strong><strong>Output: 4
</strong><strong>Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
</strong>Total amount you can rob = 1 + 3 = 4.
</code></pre>

**Example 2:**

<pre><code><strong>Input: nums = [2,7,9,3,1]
</strong><strong>Output: 12
</strong><strong>Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
</strong>Total amount you can rob = 2 + 9 + 1 = 12.
</code></pre>

### 解答 <a href="#ti-jie" id="ti-jie"></a>

* **方法 1 - DP**

範例：`nums = [2,7,9,3,1]`

當 `i = 0` 時，最多能偷的錢為 `2`

當 `i = 1` 時，最多能偷的錢為 `7`

當 `i = 2` 時，最多能偷的錢為 `11` (2+9)

當 `i = 3` 時，最多能偷的錢為 `11` (2+9)

當 `i = 4` 時，最多能偷的錢為 `12` (2+9+1)

觀察上面規律可以發現，到第 i 天為止，能夠最多偷到錢的可能有以下兩種：

1. 第 i - 2 天能偷到的最多錢 + 第 i 天偷的錢
2. 第 i - 1 天能偷到的最多錢

接著只要判斷 1. 及 2. 的方式哪一個偷到的錢最多，一直去更新 DP 就好

```javascript
var rob = function (nums) {
    const dp = [nums[0]];
    let max = nums[0];

    for (let i = 1; i < nums.length; i++) {
        const value = nums[i];
        if (i === 1) {
            dp[i] = Math.max(nums[0], nums[1]);
        } else {
            // 1. dp[i - 2] + value
            // 2. dp[i - 1]
            dp[i] = Math.max(dp[i - 2] + value, dp[i - 1]);
        }
        max = Math.max(max, dp[i]);
    }

    return max;
};
```

**參考資料**

{% embed url="<https://leetcode.wang/leetcode-198-House-Robber.html>" %}
