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
Removing Minimum Number of Magic Beans INPUT Magic Bags with Beans: 4 1 6 5 beans = [4, 1, 6, 5] Total beans: 4+1+6+5 = 16 Goal: Make all non-empty bags have equal beans with minimum removals Sorted: [1, 4, 5, 6] Prefix sum: [1, 5, 10, 16] ALGORITHM STEPS 1 Sort Array Sort beans ascending [1, 4, 5, 6] 2 Calculate Prefix Sum Cumulative sum for removal calculation 3 Try Each Target For each sorted value, calculate removals needed Target | Removed | Keep t=1: prefix[0]=1, keep 1*4=4 R=12 t=4: prefix[1]=5, keep 4*3=12 R=4 t=5: prefix[2]=10, keep 5*2=10 R=6 t=6: prefix[3]=16, keep 6*1=6 R=10 4 Return Minimum min(12, 4, 6, 10) = 4 FINAL RESULT Optimal: All bags have 4 beans 4 empty 0 4 4 Beans removed: Bag1: 0, Bag2: 1, Bag3: 2, Bag4: 1 Total: 0 + 1 + 2 + 1 = 4 OUTPUT 4 Verification [OK] Non-empty bags: [4, 4, 4] All equal - Correct! Key Insight: Sort the array and try each unique value as the target. For target at index i, remove all beans from bags with fewer beans (prefix sum), and reduce bags with more beans to target value. Formula: removed = prefix[i] + (total - prefix[i]) - beans[i] * (n - i). Time: O(n log n), Space: O(n) TutorialsPoint - Removing Minimum Number of Magic Beans | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen