#3492

Maximum Containers on a Ship

Easy
MathGreedyMathematical Optimization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

Instead of checking each cell, we can directly calculate the maximum number of containers based on the weight limit and the grid size.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate total cells as n * n.
  2. 2Step 2: Calculate maximum containers as maxWeight / w.
  3. 3Step 3: Return the minimum of total cells and maximum containers.
solution.py4 lines
1def maxContainers(n, w, maxWeight):
2    total_cells = n * n
3    max_containers = maxWeight // w
4    return min(total_cells, max_containers)

Complexity note: Direct calculations lead to O(1) complexity since we don't iterate through cells.

  • 1Total cells are n squared.
  • 2Weight limits dictate the maximum number of containers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.