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

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。