You're a wizard managing a collection of magic bean bags! Each bag contains a different number of precious magic beans, represented by the array beans.
Your goal is to make all non-empty bags contain exactly the same number of beans. You can remove beans from any bag, but you cannot add beans or move them between bags. Once removed, beans are gone forever! ๐ซโจ
The challenge: Find the minimum number of beans you need to remove to achieve this magical balance.
Note: You can completely empty some bags (remove all beans), but all remaining non-empty bags must have the same count.
Input & Output
Visualization
Time & Space Complexity
O(n log n) for sorting, then O(n) to test each potential target with constant-time cost calculation
Only using constant extra space for variables (excluding input array)
Constraints
- 1 โค beans.length โค 105
- 1 โค beans[i] โค 105
- All integers in the array are positive
- You can remove beans from any bag or empty bags completely