You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/2100-2199/2171.Removing Minimum Number of Magic Beans/README_EN.md
+21-19
Original file line number
Diff line number
Diff line change
@@ -53,28 +53,29 @@ There are no other solutions that removes 7 beans or fewer.
53
53
54
54
## Solutions
55
55
56
-
### Solution 1
56
+
### Solution 1: Sorting + Enumeration
57
+
58
+
We can sort all the beans in the bags in ascending order, and then enumerate the number of beans $beans[i]$ in each bag as the final number of beans in the bag. The total remaining number of beans is $beans[i] \times (n - i)$, so the number of beans that need to be taken out is $s - beans[i] \times (n - i)$, where $s$ is the total number of beans in all bags. We need to find the minimum number of beans that need to be taken out among all schemes.
59
+
60
+
The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the number of bags.
57
61
58
62
<!-- tabs:start -->
59
63
60
64
```python
61
65
classSolution:
62
66
defminimumRemoval(self, beans: List[int]) -> int:
63
67
beans.sort()
64
-
ans = s =sum(beans)
65
-
n =len(beans)
66
-
for i, v inenumerate(beans):
67
-
ans =min(ans, s - v * (n - i))
68
-
return ans
68
+
s, n =sum(beans), len(beans)
69
+
returnmin(s - x * (n - i) for i, x inenumerate(beans))
69
70
```
70
71
71
72
```java
72
73
classSolution {
73
74
publiclongminimumRemoval(int[] beans) {
74
75
Arrays.sort(beans);
75
76
long s =0;
76
-
for (intv: beans) {
77
-
s +=v;
77
+
for (intx: beans) {
78
+
s +=x;
78
79
}
79
80
long ans = s;
80
81
int n = beans.length;
@@ -94,7 +95,9 @@ public:
94
95
long long s = accumulate(beans.begin(), beans.end(), 0ll);
95
96
long long ans = s;
96
97
int n = beans.size();
97
-
for (int i = 0; i < n; ++i) ans = min(ans, s - 1ll * beans[i] * (n - i));
0 commit comments