Problem Description
Given an array of apple weights, determine the maximum number of apples that can be put into a basket such that their total weight does not exceed 5000 units.
Key Insights
- Sort the apple weights in non-decreasing order.
- Pick apples from the lightest until adding another apple would exceed the basket's capacity.
- Using a greedy approach guarantees maximizing the count.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the array. Space Complexity: O(1) if sorting is done in-place (or O(n) depending on the sorting algorithm implementation).
Solution
We first sort the array of weights so that we can add the lightest apples first. This is based on the greedy approach where adding smaller weights maximizes the count before reaching the capacity limit of 5000. We then iterate through the sorted array, keeping a cumulative sum of weights and a counter of the apples added. If adding the next apple exceeds the capacity, we stop and return the count. This method ensures that we have the maximum number of apples without overshooting the weight limit.