We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Apple Redistribution into Boxes

Number: 3334

Difficulty: Easy

Paid? No

Companies: Apple


Problem Description

Given an array apple of size n where each element represents a pack of apples and an array capacity of size m where each element represents the capacity of a box, determine the minimum number of boxes required to redistribute all the apples from the packs. Note that apples from the same pack can be distributed into different boxes.


Key Insights

  • Compute the total number of apples by summing the values in the apple array.
  • To minimize the number of boxes, choose boxes with the largest capacities first.
  • Sort the capacity array in descending order.
  • Recursively add box capacities until the cumulative capacity is greater than or equal to the total apples.
  • This greedy approach ensures the optimal solution using minimal boxes.

Space and Time Complexity

Time Complexity: O(m log m) due to sorting the capacity array, where m is the number of boxes.
Space Complexity: O(1) extra space if sorting is done in-place.


Solution

The solution starts by summing all apples in the input array apple. The capacity array is then sorted in descending order, allowing the selection of the largest boxes first. Iterate through this sorted capacity list, accumulating the capacity until it is at least equal to the total apple count. The number of iterations (boxes) used will be the answer. The key data structures include simple integer variables and an array. The greedy algorithm is optimal here because it ensures that the highest capacities are chosen to reach the required sum as quickly as possible.


Code Solutions

Python code:

JavaScript code:

C++ code:

Java code:

def min_boxes(apple, capacity):
    # Calculate total number of apples
    total_apples = sum(apple)
    # Sort capacities in descending order for optimal box selection
    capacity.sort(reverse=True)
    cumulative_capacity = 0
    box_count = 0
    # Iterate over sorted capacity list
    for cap in capacity:
        cumulative_capacity += cap    # Add the current box capacity
        box_count += 1                # Count the box
        if cumulative_capacity >= total_apples:
            break                   # Enough capacity reached
    return box_count

# Example usage:
print(min_boxes([1, 3, 2], [4, 3, 1, 5, 2]))  # Output: 2
print(min_boxes([5, 5, 5], [2, 4, 2, 7]))       # Output: 4
← Back to All Questions