example: Minimum boxes - rFronteddu/general_wiki GitHub Wiki

Alex is shipping the last container of the day, trying to load all n boxes into the container with their sizes represented in the array boxes.

The container may not have enough capacity for all the boxes. So some of the boxes may have to be removed. The boxes in the container must satisfy the condition:

  • max(boxes) ≤ capacity * min(boxes)

Given the array, boxes, and capacity, find the minimum number of boxes that need to be removed.

Function Description

  • getMinimumBoxes has the following parameters:
    • int[] boxes : an array of integers representing the sizes of the boxes
    • int capacity : the capacity index of the container

Approach:

  • First we sort the boxes by box size.
  • Next, we use a two pointer approach to process sequences of boxes.
    • Until l <= r, if box[j] (current max box) > capacity * box[i] (current min box) we increment the left pointer.
    • At this point the condition is verified and we can update the box counter, maxValidBoxes = max(maxValidBoxes, j - i + 1)
  • Once we process all the boxes we can return total boxes - maxValidBoxes to know the number of boxes excluded from the container.
import java.util.Arrays;

public class ShippingBoxes {
    public static int getMinimumBoxes (int[] boxes, int capacity) {
        // Step 1: Sort the array to make it easier to find valid subsets
        Arrays.sort(boxes);
        
        int n = boxes.length;
        int maxValidBoxes = 0;

        // Step 2: Use two pointers (i, j) to find the largest valid subset
        int i = 0;
        for (int j = 0; j < n; j++) {
            // Check if the condition is satisfied for the current range [i, j]
            while (i <= j && boxes[j] > capacity * boxes[i]) {
                i++; // Move i to the right until the condition is satisfied
            }
            // Update the maximum number of valid boxes found so far
            maxValidBoxes = Math.max(maxValidBoxes, j - i + 1);
        }

        // Step 3: The minimum number of boxes to remove is total boxes - maxValidBoxes
        return n - maxValidBoxes;
    }

    public static void main(String[] args) {
        // Example test case
        int[] boxes = {10, 2, 5, 7, 9};
        int capacity = 3;

        int result = getMinimumBoxes(boxes, capacity);
        System.out.println("Minimum boxes to remove: " + result);  // Expected output
    }
}