150强访谈中等

入室强盗 II

“House Robber II”问题的详细指南和 Python 实现。

问题陈述

中等

你是一名职业强盗,计划抢劫街道上的房屋。每个房子都藏有一定数量的钱。这个地方的所有房子都排列成一个圆圈。这意味着第一栋房子是最后一栋的邻居。同时,相邻的房屋都连接有安全系统,如果当晚两栋相邻的房屋被闯入,该系统会自动联系警方。

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

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

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

示例

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

You cannot rob house 1 and house 3 because they are adjacent in the circular layout.

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

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

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 资源

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