#2171
Removing Minimum Number of Magic Beans
MediumArrayGreedySortingEnumerationPrefix SumGreedySortingPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal solution leverages sorting and prefix sums to efficiently calculate the minimum beans to remove. By sorting the bags, we can easily determine how many beans to remove for each potential target based on the number of bags that would remain non-empty.
⚙️
Algorithm
4 steps- 1Step 1: Sort the array of beans in ascending order.
- 2Step 2: Calculate the prefix sums of the sorted array to quickly compute the total number of beans in the remaining bags.
- 3Step 3: Iterate through the sorted array, and for each bag, calculate the total beans to remove if we decide to keep all bags from this point onward.
- 4Step 4: Keep track of the minimum removal count.
solution.py8 lines
1def minimumBeans(beans):
2 beans.sort()
3 total_beans = sum(beans)
4 min_removal = float('inf')
5 for i in range(len(beans)):
6 removal = total_beans - (len(beans) - i) * beans[i]
7 min_removal = min(min_removal, removal)
8 return min_removalℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(1) since we are using a constant amount of extra space.
- 1Choosing the right target for equalization is crucial; it should be based on the bags with the least beans.
- 2Sorting helps in efficiently determining how many beans to remove, as it allows us to use prefix sums.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.