Minimum boxes required to carry all gifts

By | September 30, 2023

Given an array containing weights of gifts, and an integer representing maximum weight a box can contain. Each box carries at most 2 gifts at the same time, provided the sum of the weight of those gifts is at most limit of box. The task is to find the minimum number of boxes required to carry all gifts.

Note: It is guaranteed each gift can be carried by a box.

Examples:

Input: A = [4, 3, 2, 1], K = 4
Output: 3
Explanation:
4 boxes with weights (1, 3), (2), (3), and (4)

Input: A = [2, 5, 3, 4], K = 5
Output: 3
Explanation:
3 boxes with weights (2, 3), (4), and (5)

Recommended: What is stdio.h and why do we use?

Approach:

  1. Check if heavy gift fits with light one in a box.
  2. If heavy gift can’t fit, it gets its box.
  3. Pairing light and heavy gifts saves space efficiently.
  4. Iterate from lightest to heaviest gifts, check if they fit in one box.
  5. If total weight is less than K, put them in a box.

Below is the implementation of above approach:

// CPP implementation of above approach
#include <bits/stdc++.h>
using namespace std;

// Function to return number of boxes
int numBoxes(int A[], int n, int K) {

    sort(A, A + n);

    int i = 0, j = n - 1;
    int ans = 0;

    while (i <= j) {
        ans++;
        if (A[i] + A[j] <= K)
            i++;
        j--;
    }

    return ans;
}

// Driver program
int main(){

    int A[] = {4, 3, 2, 1}, K = 4;

    int n=sizeof(A)/sizeof(A[0]);

    // Print required answer
    cout << numBoxes(A,n,K);

    return 0;
}

Output:

3

Time Complexity: O(nlogn), where n is the length of array.

Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.