Skip to content

2171. Removing Minimum Number of Magic Beans 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  long long minimumRemoval(vector<int>& beans) {
    const long n = beans.size();
    const long sum = accumulate(beans.begin(), beans.end(), 0L);
    long ans = LONG_MAX;

    ranges::sort(beans);

    for (int i = 0; i < n; ++i)
      ans = min(ans, sum - (n - i) * beans[i]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public long minimumRemoval(int[] beans) {
    final long n = beans.length;
    final long sum = Arrays.stream(beans).asLongStream().sum();
    long ans = Long.MAX_VALUE;

    Arrays.sort(beans);

    for (int i = 0; i < n; ++i)
      ans = Math.min(ans, sum - (n - i) * beans[i]);

    return ans;
  }
}
1
2
3
4
5
6
class Solution:
  def minimumRemoval(self, beans: list[int]) -> int:
    n = len(beans)
    summ = sum(beans)
    return min(summ - (n - i) * bean
               for i, bean in enumerate(sorted(beans)))