How Many Apples Can You Put into the Basket Problem
Description
LeetCode Problem 1196.
You have some apples and a basket that can carry up to 5000 units of weight.
Given an integer array weight where weight[i] is the weight of the i^th apple, return the maximum number of apples you can put in the basket.
Example 1:
Input: weight = [100,200,150,1000]
Output: 4
Explanation: All 4 apples can be carried by the basket since their sum of weights is 1450.
Example 2:
Input: weight = [900,950,800,1000,700,800]
Output: 5
Explanation: The sum of weights of the 6 apples exceeds 5000 so we choose any 5 of them.
Constraints:
1 <= weight.length <= 10^31 <= weight[i] <= 10^3
Solution
Approach: Greedy, Lightest First
To fit as many apples as possible, take the lightest ones. If an optimal choice of c apples used a heavier apple while a lighter one was left out, swapping them keeps the count and does not increase the weight, so the c lightest apples also fit.
Sort weight and add the apples from the lightest one. As soon as the running total goes over 5000, the apples before the current one are the answer. If the total never goes over, all apples fit.
In JavaScript, remember that sort() without a comparator sorts numbers as strings ([100, 20] stays in that order), so pass (a, b) => a - b.
Complexity: O(n log n) time for the sort, O(1) extra space besides the sort.
class Solution:
def maxNumberOfApples(self, weight: List[int]) -> int:
weight.sort() # lightest apples first
total = 0
for i, w in enumerate(weight):
total += w
if total > 5000:
return i # apples 0..i-1 fit, apple i does not
return len(weight)