Maximum Containers on a Ship - Problem

You're the cargo operations manager for a shipping company, and you need to maximize the number of containers loaded onto a cargo ship.

Given:

  • n - the dimensions of an n × n cargo deck
  • w - the weight of each container (all containers weigh exactly the same)
  • maxWeight - the ship's maximum weight capacity

Each cell on the deck can hold exactly one container. Your goal is to determine the maximum number of containers you can load without exceeding the ship's weight limit.

Example: If you have a 3×3 deck (9 possible positions), each container weighs 5 units, and your ship can carry at most 20 units, you can load at most 20 ÷ 5 = 4 containers.

Input & Output

example_1.py — Basic Case
$ Input: n = 3, w = 5, maxWeight = 20
Output: 4
💡 Note: We have a 3×3 deck (9 positions total). Each container weighs 5 units. Maximum capacity is 20 units. We can load at most 20 ÷ 5 = 4 containers, which is less than the 9 available positions.
example_2.py — Weight Constraint
$ Input: n = 5, w = 10, maxWeight = 15
Output: 1
💡 Note: We have a 5×5 deck (25 positions total). Each container weighs 10 units. Maximum capacity is 15 units. We can only load 15 ÷ 10 = 1 container (integer division), even though we have 25 positions available.
example_3.py — Space Constraint
$ Input: n = 2, w = 3, maxWeight = 100
Output: 4
💡 Note: We have a 2×2 deck (4 positions total). Each container weighs 3 units. Maximum capacity is 100 units. Theoretically we could load 100 ÷ 3 = 33 containers, but we're limited by deck space to only 4 containers.

Constraints

  • 1 ≤ n ≤ 103
  • 1 ≤ w ≤ 104
  • 1 ≤ maxWeight ≤ 2 × 106
  • All containers have identical weight w

Visualization

Tap to expand
Container Loading: Two ConstraintsWeight ConstraintShip Capacity: 20 unitsContainer Weight: 5 units eachMax Containers = 20 ÷ 5 = 4Too heavy!Space ConstraintDeck Size: 3×3 = 9 positions4 containers5 empty spotsFinal Answermin(4, 9) = 4 containersLimited by weight, not space💡 Key Insight: Always take the minimum of both constraints!
Understanding the Visualization
1
Calculate Weight Constraint
Divide total weight capacity by individual container weight
2
Calculate Space Constraint
Count total available positions on the n×n deck
3
Choose Minimum
The smaller value is our answer - we're limited by the tighter constraint
Key Takeaway
🎯 Key Insight: This problem demonstrates that sometimes the most efficient algorithm is pure mathematics - O(1) time complexity by recognizing the dual constraint nature of the problem.
Asked in
Amazon 45 Google 32 Microsoft 28 Meta 15
23.5K Views
Medium Frequency
~5 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen