# 打家劫舍I

## [LeetCode 198. 打家劫舍](https://leetcode-cn.com/problems/house-robber/)

### 题目

```javascript
你是一个专业的小偷，计划偷窃沿街的房屋。每间房内都藏有一定的现金，影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统，如果两间相邻的房屋在同一晚上被小偷闯入，系统会自动报警。

给定一个代表每个房屋存放金额的非负整数数组，计算你 不触动警报装置的情况下 ，一夜之内能够偷窃到的最高金额。



示例 1：

输入：[1,2,3,1]
输出：4
解释：偷窃 1 号房屋 (金额 = 1) ，然后偷窃 3 号房屋 (金额 = 3)。
     偷窃到的最高金额 = 1 + 3 = 4 。
示例 2：

输入：[2,7,9,3,1]
输出：12
解释：偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9)，接着偷窃 5 号房屋 (金额 = 1)。
     偷窃到的最高金额 = 2 + 9 + 1 = 12 。
```

### 题解

#### DP

```javascript
function rob(nums: number[]): number {
    // dp[i]=max(dp[i-2]+nums[i],dp[i-1])=最大金额
    // dp[0]=nums[0],dp[1]=max(nums[0].nums[1]))

    let dp_0:number = nums[0],
        dp_1:number = Math.max(nums[0],nums[1]),
        dp_i:number = 0,
        len:number = nums.length;

    if(len<3) return len<2 ? dp_0 : dp_1

    for(let i=2;i<len;i++){
        dp_i = Math.max(dp_0+nums[i],dp_1);
        dp_0 = dp_1;
        dp_1 = dp_i
    }

    return dp_i
};
```


---

# 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://voyz.gitbook.io/voyz-algorithm/dong-tai-gui-hua/da-jia-jie-she-i.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.
