LeetCode 3492: Maximum Containers on a Ship (Greedy / Math)
LeetCode 3492Source: https://leetcode.com/problems/maximum-containers-on-a-ship/
English
If the ship has n * n slots, each container weighs w, and total allowed weight is maxWeight, then the answer is limited by both slot count and weight budget. So we compute min(n * n, maxWeight / w).
class Solution {
public int maxContainers(int n, int w, int maxWeight) {
long slots = 1L * n * n;
long byWeight = maxWeight / w;
return (int)Math.min(slots, byWeight);
}
}func maxContainers(n int, w int, maxWeight int) int {
slots := n * n
byWeight := maxWeight / w
if byWeight < slots {
return byWeight
}
return slots
}class Solution {
public:
int maxContainers(int n, int w, int maxWeight) {
long long slots = 1LL * n * n;
long long byWeight = maxWeight / w;
return (int)min(slots, byWeight);
}
};class Solution:
def maxContainers(self, n: int, w: int, maxWeight: int) -> int:
slots = n * n
by_weight = maxWeight // w
return min(slots, by_weight)function maxContainers(n, w, maxWeight) {
const slots = n * n;
const byWeight = Math.floor(maxWeight / w);
return Math.min(slots, byWeight);
}中文
船最多只能放 n * n 个箱子,每个箱子重量是 w,总重量不能超过 maxWeight。因此答案同时受「格子数」和「重量上限」约束,直接取 min(n * n, maxWeight / w) 即可。
class Solution {
public int maxContainers(int n, int w, int maxWeight) {
long slots = 1L * n * n;
long byWeight = maxWeight / w;
return (int)Math.min(slots, byWeight);
}
}func maxContainers(n int, w int, maxWeight int) int {
slots := n * n
byWeight := maxWeight / w
if byWeight < slots {
return byWeight
}
return slots
}class Solution {
public:
int maxContainers(int n, int w, int maxWeight) {
long long slots = 1LL * n * n;
long long byWeight = maxWeight / w;
return (int)min(slots, byWeight);
}
};class Solution:
def maxContainers(self, n: int, w: int, maxWeight: int) -> int:
slots = n * n
by_weight = maxWeight // w
return min(slots, by_weight)function maxContainers(n, w, maxWeight) {
const slots = n * n;
const byWeight = Math.floor(maxWeight / w);
return Math.min(slots, byWeight);
}
Comments