Taro Logo

How Many Apples Can You Put into the Basket

Easy
Asked by:
Virtu Financial
0 views
Topics:
ArraysGreedy Algorithms

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 ith 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 <= 103
  • 1 <= weight[i] <= 103

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the weights of the apples be decimals/floats, or are they strictly guaranteed to be integers?
  2. What should be returned if the array is empty, or if even the lightest apple exceeds the 5000-unit capacity?
  3. Can the array contain negative numbers or zeros, and are we guaranteed that all weights are positive?
  4. Are duplicates allowed in the input array, and if so, should identical weights be treated as distinct individual apples?
  5. Is the 5000-unit capacity strictly a limit on the sum of the weights, or is there also a physical limit on the total number of apples the basket can hold?

Brute Force Solution

Approach

Imagine you have a collection of apples of different weights and a basket that can only hold a certain total weight before breaking. The brute force approach involves exploring every conceivable combination of apples to see which groups fit inside the basket without exceeding the limit.

Here's how the algorithm would work step-by-step:

  1. Start by looking at every single apple individually and check if each one fits in the basket on its own.
  2. Next, consider every possible pair of apples that can be formed from your collection.
  3. Then, check every possible group of three apples, and continue this process for groups of four, five, and so on, building up to larger and larger groups.
  4. For every single combination you test, add up the weights of the apples in that group.
  5. Compare the total weight of each group against the maximum weight the basket can safely hold.
  6. Keep a mental note of how many apples were in the largest group you tested whose total weight did not exceed the limit.
  7. After you have thoroughly checked every single possible combination of apples, declare the size of the largest successful group as your final answer.

Code Implementation

def max_apples_in_basket(apple_weights, weight_limit):
    maximum_apple_count = 0
    
    # Generate every possible combination size to find the maximum possible fit
    for combination_size in range(1, len(apple_weights) + 1):
        from itertools import combinations
        
        for apple_group in combinations(apple_weights, combination_size):
            current_total_weight = sum(apple_group)
            
            # Validate if the current group weight stays within the basket limit
            if current_total_weight <= weight_limit:
                if combination_size > maximum_apple_count:
                    maximum_apple_count = combination_size
                    
    return maximum_apple_count

Big(O) Analysis

Time Complexity
O(2ⁿ) – The brute force strategy requires checking every single possible combination of apples, which means evaluating the power set of the collection. For an input of n apples, there are 2ⁿ possible subsets that must be formed and tested. As the number of apples increases, the total combinations to sum and compare double with each additional apple. This exponential growth leads directly to a time complexity of O(2ⁿ).
Space Complexity
O(1) – The brute force approach described relies entirely on iterating through combinations and maintaining a few scalar variables like counters and running sums. No auxiliary data structures, recursive call stacks, or temporary collections of size N are created to store the subsets. Therefore, the extra memory used remains constant regardless of how many apples are in the input collection.

Optimal Solution

Approach

To fit the maximum number of apples into your basket, the strategy is to always pick up the lightest available apple first. By prioritizing the smallest apples, you save as much space as possible so you can carry the highest total count before the basket reaches its weight limit.

Here's how the algorithm would work step-by-step:

  1. Gather all your apples and check how heavy each one is.
  2. Arrange the apples in order from lightest to heaviest.
  3. Start placing the apples into your basket one by one, beginning with the absolute lightest apple.
  4. Keep a running total of the combined weight of the apples you have placed inside.
  5. Stop adding apples the moment the next lightest apple would make the total weight exceed your basket limit.
  6. Count how many apples you successfully placed inside the basket and that is your maximum possible total.

Code Implementation

def max_apples_in_basket(apple_weights):
    # Sorting allows us to greedily select the lightest apples first to maximize count.
    sorted_apple_weights = sorted(apple_weights)
    
    total_basket_weight = 0
    maximum_apple_count = 0
    maximum_weight_limit = 5000

    for current_apple_weight in sorted_apple_weights:
        # We stop adding when the next apple exceeds the weight capacity of the basket.
        if total_basket_weight + current_apple_weight > maximum_weight_limit:
            break

        total_basket_weight += current_apple_weight
        maximum_apple_count += 1

    # Returning the count gives the maximum number of apples that fit within the weight limit.
    return maximum_apple_count

Big(O) Analysis

Time Complexity
O(n log n) – The time complexity is primarily driven by sorting the array of n apples from lightest to heaviest, which takes O(n log n) time using an efficient comparison-based sorting algorithm. Afterward, a single pass iterates through the sorted array to accumulate weights up to the limit, requiring linear O(n) time. As n grows, the logarithmic sorting term dominates the linear accumulation step. Therefore, the total operations approximate n log n + n, which simplifies to the final Big O of O(n log n).
Space Complexity
O(1) – The algorithm sorts the array of apple weights in place without requiring any additional data structures that scale with the input size N. We only allocate a few primitive variables to maintain the running total of the combined weight and the count of apples added. Therefore, the extra memory used remains constant regardless of how many apples are in the basket.

Edge Cases

Empty array of apple weights
How to Handle:
Return zero immediately since no apples are available to put into the basket.
Array containing a single apple whose weight exceeds 5000 units
How to Handle:
Return zero because the single apple cannot fit within the basket capacity.
Array containing a single apple whose weight is less than or equal to 5000 units
How to Handle:
Return one since that single valid apple can successfully fit into the basket.
All apples have weights larger than the maximum capacity of 5000 units
How to Handle:
Sorting and greedy accumulation will fail to add any elements, correctly resulting in a count of zero.
Total sum of all apple weights is less than or equal to 5000 units
How to Handle:
Return the total length of the array because every single apple fits inside the basket.
Weights include zero or negative numbers
How to Handle:
Filter out non-positive weights or assume valid positive inputs per problem constraints so they do not incorrectly inflate the count.
Large input size with thousands of lightweight apples
How to Handle:
An efficient sorting approach ensures logarithmic or linearithmic time complexity to scale well within performance limits.
Apple weights summing to exactly 5000 units
How to Handle:
The greedy selection sums the exact matching weights and returns the precise count of apples used.