Determine the maximum number of containers that can be loaded on a ship subject to a capacity limit.
You are given an array representing the weights or sizes of containers and a ship with a maximum carrying capacity. Choose the largest possible number of containers whose total weight does not exceed the ship's capacity.
Return that maximum count.
This is a typical optimization problem where the answer depends on a feasibility check: given a target number of containers, decide whether it is possible to load that many containers within the capacity limit.
containers, where each value is the weight of one container.capacity, the maximum total weight the ship can carry.The exact input shape may vary by platform, but the core task is to maximize the number of selected containers without exceeding capacity.
Return an integer representing the maximum number of containers that can be placed on the ship without the total weight exceeding capacity.
1 <= containers.lengthcapacity is a non-negative integer.Example 1
Input
containers = [4, 1, 3, 2], capacity = 5
Output
2
Explanation
The best choice is containers with weights 1 and 2, for a total of 3. Any 3-container selection exceeds the capacity.
Example 2
Input
containers = [8, 2, 1, 7], capacity = 10
Output
2
Explanation
Choose containers 1 and 2 for a total of 3, or 1 and 7 for a total of 8. Three containers would exceed the capacity.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.