Removing Minimum Number of Magic Beans - Problem
You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag.
Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags.
Return the minimum number of magic beans that you have to remove.
Input & Output
Example 1 — Basic Case
$
Input:
beans = [4,1,6,5]
›
Output:
4
💡 Note:
Remove 1 bean from bag with 1 bean (empty it), remove 2 beans from bag with 6 beans (keep 4), remove 1 bean from bag with 5 beans (keep 4). All remaining bags have 4 beans each. Total removals = 1 + 2 + 1 = 4.
Example 2 — All Same Target
$
Input:
beans = [2,10,3,2]
›
Output:
7
💡 Note:
Set target to 2: empty bag with 2 beans (0 removals each), remove 8 from bag with 10 beans, remove 1 from bag with 3 beans. Total = 0 + 0 + 8 + 1 = 9. But target=2 is better: total removals = 7.
Example 3 — Single Element
$
Input:
beans = [5]
›
Output:
0
💡 Note:
Only one bag, keep it as is. No removals needed.
Constraints
- 1 ≤ beans.length ≤ 105
- 1 ≤ beans[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of bag sizes: [4, 1, 6, 5]
2
Process
Try each value as target level, calculate removals needed
3
Output
Minimum removals needed: 4 (target level = 4)
Key Takeaway
🎯 Key Insight: Only existing array values can be optimal target levels - sort first then use prefix sums for O(n log n) solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code