Minimum Number of Groups to Create a Valid Assignment - Problem
You are given a collection of numbered balls and instructed to sort them into boxes for a nearly balanced distribution. There are two rules you must follow:
Rule 1: Balls with the same number must be placed in the same box. However, if you have more than one ball with the same number, you can put them in different boxes.
Rule 2: The largest box can only have one more ball than the smallest box (difference ≤ 1).
Return the minimum number of boxes needed to sort these balls following these rules.
Input & Output
Example 1 — Basic Distribution
$
Input:
nums = [1,1,2,2,3]
›
Output:
3
💡 Note:
Frequencies: 1→2, 2→2, 3→1. Need 3 groups with sizes [2,2,1] to satisfy balance constraint (max-min ≤ 1)
Example 2 — All Same Numbers
$
Input:
nums = [1,1,1,1]
›
Output:
2
💡 Note:
All balls have same number, can split into 2 groups of size 2 each: [2,2]
Example 3 — Single Element
$
Input:
nums = [5]
›
Output:
1
💡 Note:
Only one ball, so minimum is 1 group
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code