Problem Description
A ship has a cargo deck arranged as an n x n grid where each cell can hold exactly one container of weight w. However, the total weight of all containers loaded must not exceed the ship's maximum weight capacity, maxWeight. Determine the maximum number of containers that can be loaded onto the ship without exceeding the weight limit.
Key Insights
- The deck has a fixed capacity of n² cells.
- Each container weighs w, so loading x containers results in a total weight of x * w.
- The maximum number of containers allowed by the weight limit is maxWeight // w (using integer division).
- The final answer is the minimum between the deck capacity (n²) and the weight-based capacity.
Space and Time Complexity
Time Complexity: O(1)
Space Complexity: O(1)
Solution
The solution involves two simple calculations:
- Compute the deck capacity as n².
- Compute the weight-based capacity as maxWeight divided by w using integer division. Since both operations are constant time arithmetic operations, the overall complexity is O(1). The final answer is the smaller value between these two capacities. This ensures that neither the physical space nor the weight limit is exceeded.
Code Solutions
Python code:
JavaScript code:
C++ code:
Java code: