Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: beans = [4,1,6,5] Output: 4 Explanation: - We remove 1 bean from the bag with only 1 bean. This results in the remaining bags: [4,0,6,5] - Then we remove 2 beans from the bag with 6 beans. This results in the remaining bags: [4,0,4,5] - Then we remove 1 bean from the bag with 5 beans. This results in the remaining bags: [4,0,4,4] We removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans. There are no other solutions that remove 4 beans or fewer.
Example 2:
Input: beans = [2,10,3,2] Output: 7 Explanation: - We remove 2 beans from one of the bags with 2 beans. This results in the remaining bags: [0,10,3,2] - Then we remove 2 beans from the other bag with 2 beans. This results in the remaining bags: [0,10,3,0] - Then we remove 3 beans from the bag with 3 beans. This results in the remaining bags: [0,10,0,0] We removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans. There are no other solutions that removes 7 beans or fewer.
Constraints:
1 <= beans.length <= 1051 <= beans[i] <= 105Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[4,1,6,5]
[2,10,3,2]
minimum-moves-to-equal-array-elements-ii)minimum-operations-to-reduce-x-to-zero)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2171: Removing Minimum Number of Magic Beans
class Solution {
public long minimumRemoval(int[] beans) {
Arrays.sort(beans);
long s = 0;
for (int x : beans) {
s += x;
}
long ans = s;
int n = beans.length;
for (int i = 0; i < n; ++i) {
ans = Math.min(ans, s - (long) beans[i] * (n - i));
}
return ans;
}
}
// Accepted solution for LeetCode #2171: Removing Minimum Number of Magic Beans
func minimumRemoval(beans []int) int64 {
sort.Ints(beans)
s := 0
for _, x := range beans {
s += x
}
ans := s
n := len(beans)
for i, x := range beans {
ans = min(ans, s-x*(n-i))
}
return int64(ans)
}
# Accepted solution for LeetCode #2171: Removing Minimum Number of Magic Beans
class Solution:
def minimumRemoval(self, beans: List[int]) -> int:
beans.sort()
s, n = sum(beans), len(beans)
return min(s - x * (n - i) for i, x in enumerate(beans))
// Accepted solution for LeetCode #2171: Removing Minimum Number of Magic Beans
/**
* [2171] Removing Minimum Number of Magic Beans
*
* 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.
*
* Example 1:
*
* Input: beans = [4,1,6,5]
* Output: 4
* Explanation:
* - We remove 1 bean from the bag with only 1 bean.
* This results in the remaining bags: [4,<u>0</u>,6,5]
* - Then we remove 2 beans from the bag with 6 beans.
* This results in the remaining bags: [4,0,<u>4</u>,5]
* - Then we remove 1 bean from the bag with 5 beans.
* This results in the remaining bags: [4,0,4,<u>4</u>]
* We removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans.
* There are no other solutions that remove 4 beans or fewer.
*
* Example 2:
*
* Input: beans = [2,10,3,2]
* Output: 7
* Explanation:
* - We remove 2 beans from one of the bags with 2 beans.
* This results in the remaining bags: [<u>0</u>,10,3,2]
* - Then we remove 2 beans from the other bag with 2 beans.
* This results in the remaining bags: [0,10,3,<u>0</u>]
* - Then we remove 3 beans from the bag with 3 beans.
* This results in the remaining bags: [0,10,<u>0</u>,0]
* We removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans.
* There are no other solutions that removes 7 beans or fewer.
*
*
* Constraints:
*
* 1 <= beans.length <= 10^5
* 1 <= beans[i] <= 10^5
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/removing-minimum-number-of-magic-beans/
// discuss: https://leetcode.com/problems/removing-minimum-number-of-magic-beans/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn minimum_removal(beans: Vec<i32>) -> i64 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2171_example_1() {
let beans = vec![4, 1, 6, 5];
let result = 4;
assert_eq!(Solution::minimum_removal(beans), result);
}
#[test]
#[ignore]
fn test_2171_example_2() {
let beans = vec![2, 10, 3, 2];
let result = 7;
assert_eq!(Solution::minimum_removal(beans), result);
}
}
// Accepted solution for LeetCode #2171: Removing Minimum Number of Magic Beans
function minimumRemoval(beans: number[]): number {
beans.sort((a, b) => a - b);
const s = beans.reduce((a, b) => a + b, 0);
const n = beans.length;
let ans = s;
for (let i = 0; i < n; ++i) {
ans = Math.min(ans, s - beans[i] * (n - i));
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.