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

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