↓快轉到主要內容
  1. LeetCode/

LeetCode 3492: Maximum Containers on a Ship

·1 分鐘· ·
LeetCode Easy Math
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-03-23

  • 提交紀錄:Wrong Answer → Accepted ×2

解題思路
#

兩個上限取較小的:

  • 格子數:n × n。
  • 重量:每個貨櫃 w,最多 maxWeight // w 個(無條件捨去)。

我的嘗試
#

第一版用 maxWeight / w,回傳的是浮點數。例如 n = 2、w = 3、maxWeight = 7:答案是 2,回傳 2.333...。改成 int(...) 就 AC 了;直接用 // 更清楚。

正確解法
#

class Solution:
    def maxContainers(self, n: int, w: int, maxWeight: int) -> int:
        return min(n * n, maxWeight // w)

複雜度
#

時間 O(1),空間 O(1)。

要特別避免的錯誤
#

  • Python 3 的 / 是浮點除法,數量要用 //。

面試口說整理
#

能放的數量同時受格子數 n² 和重量限制 maxWeight // w 限制,取兩者較小的。時間 O(1)。

相關文章

LeetCode 1103: Distribute Candies to People
·1 分鐘
LeetCode Easy Math Simulation
LeetCode 1103 解題筆記:模擬一輪一輪發糖果,第 i 次發 i + 1 顆,不夠時把剩下的全給目前這個人
LeetCode 1137: N-th Tribonacci Number
·1 分鐘
LeetCode Easy Math Dynamic-Programming Memoization
LeetCode 1137 解題筆記:跟 Fibonacci 一樣,用三個變數滾動;小心 T0 = 0、T1 = T2 = 1 的起始值和迴圈範圍
LeetCode 1030: Matrix Cells in Distance Order
·1 分鐘
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 解題筆記:列出所有座標,按到中心的曼哈頓距離排序;回傳的是座標,不是距離
LeetCode 1025: Divisor Game
·1 分鐘
LeetCode Easy Math Dynamic-Programming Brainteaser Game-Theory
LeetCode 1025 解題筆記:dp[i] = 存在 i 的因數 x 讓 dp[i - x] 是輸;觀察後答案就是 n 是偶數
LeetCode 989: Add to Array-Form of Integer
·1 分鐘
LeetCode Easy Array Math
LeetCode 989 解題筆記:把 k 當成進位,從陣列最後一位往前加,k 還沒用完就繼續往前補位
LeetCode 908: Smallest Range I
·1 分鐘
LeetCode Easy Array Math
LeetCode 908 解題筆記:最大值往下調 k、最小值往上調 k,答案是 max(0, max - min - 2k)