Sort the fish sizes in nondecreasing order. If the smallest fish in a basket has size , every fish in that basket must have size less than . This condition is sufficient: even the largest fish cannot eat the smallest one, so every fish in the basket is safe.
Start a new basket with the smallest fish not yet placed, and let its size be . In sorted order, place all fish of size less than in this basket. When a fish of size at least is reached, start the next basket with that fish. Repeat until every fish is placed, counting the baskets created.
Keep equal to the smallest size in the current basket while adding fish. Do not replace it with the size of the most recently added fish.
Sorting takes time and the scan takes time, so the total time complexity is . Storing the array uses space.
Proof
Let be the smallest size among the fish not yet placed. Consider an optimal arrangement of these fish, and let be a basket containing a fish of size .
Every fish in must have size less than . Move every fish of size less than from the other baskets into . Each moved fish has size at least , so the smallest size in remains and its largest size remains less than . Thus, is still safe. Removing fish from the other baskets cannot make them unsafe, and the number of baskets does not increase.
Solution written by GPT6
Consequently, there is an optimal arrangement in which all remaining fish of size less than share one basket. This is exactly the first basket chosen by the greedy algorithm.
Remove this basket and apply the same argument to the remaining fish. At every step, some optimal arrangement agrees with the greedy choices. Therefore, the algorithm produces the minimum possible number of baskets.