DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord account linking.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Fish Baskets

Back to problem

Editorial

Sort the fish sizes in nondecreasing order. If the smallest fish in a basket has size mmm, every fish in that basket must have size less than KmKmKm. 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 mmm. In sorted order, place all fish of size less than KmKmKm in this basket. When a fish of size at least KmKmKm is reached, start the next basket with that fish. Repeat until every fish is placed, counting the baskets created.

Keep mmm 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 O(Nlog⁡N)O(N\log N)O(NlogN) time and the scan takes O(N)O(N)O(N) time, so the total time complexity is O(Nlog⁡N)O(N\log N)O(NlogN). Storing the array uses space.

Proof

Let mmm be the smallest size among the fish not yet placed. Consider an optimal arrangement of these fish, and let BBB be a basket containing a fish of size mmm.

Every fish in BBB must have size less than KmKmKm. Move every fish of size less than Km 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

O(N)O(N)
O(N)
Km
Km
BBB
mmm
BBB
mmm
KmKmKm
BBB

Consequently, there is an optimal arrangement in which all remaining fish of size less than KmKmKm 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.