How Many Apples Can You Put into the Basket

Updated on 02 June, 2025
How Many Apples Can You Put into the Basket header image

Problem Statement

In this scenario, you are faced with a problem of filling a basket that has a capacity to carry up to 5000 units of weight with apples. Each apple has a certain weight, and these weights are provided to you in an integer array called weight, where each entry weight[i] indicates the weight of the i-th apple. Your task is to determine the maximum number of apples you can place in the basket without exceeding its weight limit.

Examples

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

Approach and Intuition

  1. Given this problem, our primary goal is to maximize the number of apples we can carry without their combined weight exceeding 5000.

  2. To solve the problem efficiently, consider the following steps:

    1. Sort the weight array in ascending order. This sorting will help in adding apples starting from the lightest, which maximizes the quantity as we fill the basket.
    2. Initialize a variable, say currentWeight to 0, to keep track of the ongoing weight of apples in the basket.
    3. Initialize a counter, say maxApples, to count the number of apples we can carry without exceeding the limit.
    4. Iterate through the sorted apple weights:
      • Add the weight of the current apple to currentWeight.
      • If currentWeight is still less than or equal to 5000, increment the maxApples counter.
      • If adding another apple exceeds the basket's limit (currentWeight > 5000), break the loop as adding more will not be feasible.
    5. The value of maxApples at the end of this process will be your answer.

This sequential approach ensures that each step logically follows from the previous, and by prioritizing lighter apples, we optimize the number of apples we can fit into the basket.

Solutions

  • Java
  • Python
java
class Solution {
    public int maximumApples(int[] weights) {
        int maxWeight = -1;
        for (int weight : weights) {
            maxWeight = Math.max(maxWeight, weight);
        }
        int[] frequency = new int[maxWeight + 1];
        for (int weight : weights) {
            frequency[weight]++;
        }

        int totalApples = 0, currentWeight = 0;
        for (int i = 0; i <= maxWeight; i++) {
            if (frequency[i] > 0) {
                int possibleToTake = Math.min(frequency[i], (5000 - currentWeight) / i);
                if (possibleToTake == 0) {
                    break;
                }
                currentWeight += possibleToTake * i;
                totalApples += possibleToTake;
            }
        }
        return totalApples;
    }
}

In the Java-based solution provided, the goal is to determine the maximum number of apples you can carry in a basket without exceeding a weight limit of 5000 units. The approach uses a greedy algorithm and the following steps outline the implementation:

  1. Initialize maxWeight to -1 to find the heaviest apple by iterating over the input apple weights array and updating maxWeight using the built-in Math.max() function.

  2. Create a frequency array to count occurrences of each weight. The size of the array is maxWeight + 1 (to account for all weights from 0 to maxWeight), and the array is populated by iterating through the weights again.

  3. Set totalApples initially to 0, representing the count of apples in the basket, and currentWeight to 0, representing the current total weight of the basket. Proceed through each unique apple weight from lightest to heaviest.

  4. For each weight in the frequency array:

    • Calculate possibleToTake, the maximum number of apples of that weight that can still fit in the basket without exceeding the 5000 unit limit. This is determined by taking the minimum between how many apples of that weight are available (frequency[i]) and how many apples of that weight can fit given the remaining capacity of the basket.
    • If no apples of that weight can be added (i.e., possibleToTake is zero), exit the loop as adding heavier apples would also exceed the limit.
    • Add the product of possibleToTake and the apple weight to currentWeight and add possibleToTake to totalApples.
  5. Return totalApples, which now contains the maximum number of apples that fit within the weight limit.

This algorithm effectively compiles the maximum number of apples that can be placed in the basket without surpassing the total weight allowance, ensuring that as many apples are included as possible until the weight limit is hit or all weight categories are evaluated.

python
class Solution:
    def maximumApples(self, weights: List[int]) -> int:
        max_size = max(weights) + 1
        fruit_counts = [0] * max_size
        for weight in weights:
            fruit_counts[weight] += 1

        total_apples = total_weight = 0
        for idx in range(max_size):
            if fruit_counts[idx] > 0:
                available_to_take = min(fruit_counts[idx], (5000 - total_weight) // idx)
                if available_to_take == 0:
                    break

                total_apples += available_to_take
                total_weight += available_to_take * idx
        return total_apples

The Python code provided calculates the maximum number of apples that can be placed into a basket, given the constraints on total weight. They key idea in the solution is to use a greedy algorithm that leverages sorting and counting each apple's weight. Here’s a breakdown of the steps taken:

  1. First, determine the maximum weight among all the apples for creating a list long enough to track all possible weights.
  2. Create a list fruit_counts to count how many apples exist for each weight.
  3. Iterate through the apple weights updating the fruit_counts list to reflect the number of apples for each specific weight.
  4. Initialize total_apples and total_weight to zero, which will keep track of the total apples in the basket and their cumulative weight.
  5. Iterate through the weights. For each weight, calculate the maximum number of apples that can be added without exceeding the total allowed weight of 5000.
  6. If adding apples of a particular weight would exceed the weight limit, skip to the next lighter apple (if any), otherwise add as many apples as possible up to either their available count or the maximum that the basket can still handle.
  7. Return the total number of apples (total_apples) that can be put into the basket without exceeding the weight limit of 5000.

The solution is optimal and efficiently handles the problem by considering apples based on their weight, ensuring that the basket carries the maximum number of apples possible within the given weight constraint.

Comments

No comments yet.