We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum Containers on a Ship

Number: 3817

Difficulty: Easy

Paid? No

Companies: N/A


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:

  1. Compute the deck capacity as n².
  2. 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:

# Function to calculate the maximum number of containers that can be loaded on the ship.
def maximumContainers(n, w, maxWeight):
    # Calculate the total number of cells on the deck (deck capacity).
    deck_capacity = n * n
    # Calculate the maximum number of containers allowed based on the weight constraint.
    weight_based_capacity = maxWeight // w
    # Return the minimum of the two capacities.
    return min(deck_capacity, weight_based_capacity)

# Example usage:
print(maximumContainers(2, 3, 15))  # Expected output: 4
print(maximumContainers(3, 5, 20))  # Expected output: 4
← Back to All Questions