Given an array containing weights of gifts, and an integer K representing maximum weight a box can contain (All boxes are uniform). 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.
Input: A = [3, 2, 2, 1], K = 3
Explanation: 3 boxes with weights (1, 2), (2) and (3)
Input: A = [3, 5, 3, 4], K = 5
Explanation: 4 boxes with weights (3), (3), (4), (5)
Approach: If the heaviest gift can share a box with the lightest gift, then do so. Otherwise, the heaviest gift can’t pair with anyone, so it get an individual box.
The reason this works is because if the lightest gift can pair with anyone, it might as well pair with the heaviest gift.
Let A[i] be the currently lightest gift, and A[j] to the heaviest.
Then, if the heaviest gift can share a box with the lightest gift (if A[j] + A[i] <= K) then do so otherwise, the heaviest gift get an individual box.
Below is the implementation of above approach:
Time Complexity: O(N*log(N)), where N is the length of array.
- Minimum time required to transport all the boxes from source to the destination under the given constraints
- Minimum number of stacks possible using boxes of given capacities
- Minimum Swaps required to group all 1's together
- Minimum changes required to make two arrays identical
- Minimum changes required such that the string satisfies the given condition
- Minimum number of changes required to make the given array an AP
- Minimum operations required to change the array such that |arr[i] - M| <= 1
- Minimum number of operations required to reduce N to 1
- Minimum operations required to remove an array
- Minimum swaps required to bring all elements less than or equal to k together
- Minimum deletions required such that any number X will occur exactly X times
- Minimum number of bottles required to fill K glasses
- Minimum number of swaps required to sort an array | Set 2
- Minimum no. of operations required to make all Array Elements Zero
- Minimum number of days required to complete the work
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.