There are n objects having different weights. We have to find the minimum number of boxes required to pack all weights where each box can have the maximum weight of K. Boxes can have any number of objects but weight should be less than or equal to given weight K.
All weights are less than or equal to K.
For example, let K= 10 and objects be {1,2,3,6,8} than minimum number of boxes required are 2 ,i.e, {8,2}, {1,3,6}
How should I approach this problem?
The Next Fit Decreasing (NFD) algorithm is an efficient method for arranging items into boxes, maximizing box utilization while minimizing the number of boxes used. To implement this algorithm, follow these steps:
Sort the items in descending order of weight. This ensures that heavier items are considered first during the packing process.
Initialize an array of boxes, each containing its remaining capacity (initially set to the box capacity).
Iterate through the sorted items and, for each item:
If the item's weight exceeds the box capacity, skip it as it cannot fit into any box.
Otherwise, start a nested loop to find a suitable box with enough remaining capacity to hold the item's weight.
If a valid box is found, place the item in it and update the remaining capacity of the box.
If no valid box is found, create a new box and place the item in it.
After processing all the items, you'll have a list of boxes with packed items and their respective remaining capacities.
just pass items and max capacity of box as input as like below
I hope this one helps to you.
Happy Coding :)