Problem · Array
Maximum Apples That Fit in a Box
Learn this problemProblem statement
A box can hold at most 5000 grams and may already contain some items. You want to add as many apples as possible without exceeding the box's capacity.
You are given a zero-indexed integer array a:
a[0]is the total weight, in grams, of the items already in the box.- For every
i >= 1,a[i]is the weight, in grams, of one available apple.
Return the maximum number of available apples that can be added to the box without making its total weight exceed 5000 grams.
Function
maximumApples(a: int[]) → intExamples
Example 1
a = [4650,150,150,150]return = 2The box already contains 4650 grams, leaving 350 grams of capacity. Two apples weighing 150 grams each fit, bringing the total to 4950 grams. A third apple would exceed the capacity, so the answer is 2.
Constraints
1 <= a.length <= 1000 <= a[i] <= 5000