150强访谈中等

入室抢劫者

“入室抢劫”问题的详细指南和 Python 实现。

问题陈述

中等

你是一名职业强盗,计划抢劫街道上的房屋。每栋房子都藏有一定数量的钱,唯一阻止你抢劫的限制是相邻的房子都有安全系统连接,如果相邻的两栋房子在同一天晚上被闯入,它会自动联系警方。

给定一个表示每栋房子的金额的整数数组 nums,返回今晚您可以在不通知警察的情况下抢劫的最大金额。

编写一个函数 rob(nums: List[int]) -> int

约束条件
  • 1 <= len(nums) <= 100
  • 0 <= nums[i] <= 400

示例

Example 1
Input
nums = [1,2,3,1]
Output
4
Explanation

Rob house 1 (money = 1) then rob house 3 (money = 3). Total = 1 + 3 = 4.

Example 2
Input
nums = [2,7,9,3,1]
Output
12
Explanation

Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total = 12.

Need a Hint?
考虑使用一维 DP 特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。