150強訪談簡單

裝最多水的容器

「裝有最多水的容器」問題的詳細指南和 Python 實作。

問題陳述

簡單

給您一個長度為 n 的整數陣列 height。繪製了 n 條垂直線,使得第 i 線的兩個端點是 (i, 0)(i, height[i])

求與 x 軸一起形成容器的兩條線,使得該容器包含最多的水。

返回容器可以儲存的最大水量。

請注意,您不能傾斜容器。

寫一個函數 maxArea(height: List[int]) -> int

約束條件
  • n == len(height)
  • 2 <= n <= 10^5
  • 0 <= height[i] <= 10^4

範例

Example 1
Input
height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output
49
Explanation

The max area is between lines at index 1 (height 8) and index 8 (height 7). Area = min(8, 7) * (8 - 1) = 7 * 7 = 49.

Example 2
Input
height = [1, 1]
Output
1
Explanation

Area = min(1, 1) * (1 - 0) = 1.

Need a Hint?
考慮使用特定於兩個指標的資料結構,例如集合或堆。
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 資源

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