150強訪談中等

氣球爆裂

「氣球爆裂」問題的詳細指南和 Python 實作。

問題陳述

中等

給你 n 個氣球,索引從 0 到 n - 1。每個氣球上都畫有一個數字,用陣列 nums 表示。你被要求爆破所有的氣球。

如果你戳破第 i 個氣球,你將獲得 nums[i - 1] * nums[i] * nums[i + 1] 個硬幣。如果 i - 1 或 i + 1 超出了數組的範圍,則將其視為氣球,上面畫有 1。

透過明智地爆破氣球,返還您可以收集到的最大硬幣。

寫一個函數 maxCoins(nums: List[int]) -> int

約束條件
  • n == len(nums)
  • 1 <= n <= 300
  • 0 <= nums[i] <= 100

範例

Example 1
Input
nums = [3,1,5,8]
Output
167
Explanation

burst 1 -> burst 5 -> burst 3 -> burst 8. Coins: 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167.

Example 2
Input
nums = [1,5]
Output
10
Explanation

burst 1 first: 1*5*1 = 5, then burst 5: 1*5*1 = 5. Total = 10.

Need a Hint?
考慮使用 2D 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 資源

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