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/1500-1599/1551.Minimum Operations to Make Array Equal/README_EN.md
+39-17
Original file line number
Diff line number
Diff line change
@@ -6,22 +6,14 @@
6
6
7
7
<p>You have an array <code>arr</code> of length <code>n</code> where <code>arr[i] = (2 * i) + 1</code> for all valid values of <code>i</code> (i.e. <code>0 <= i < n</code>).</p>
8
8
9
-
10
-
11
9
<p>In one operation, you can select two indices <code>x</code> and <code>y</code> where <code>0 <= x, y < n</code> and subtract <code>1</code> from <code>arr[x]</code> and add <code>1</code> to <code>arr[y]</code> (i.e. perform <code>arr[x] -=1 </code>and <code>arr[y] += 1</code>). The goal is to make all the elements of the array <strong>equal</strong>. It is <strong>guaranteed</strong> that all the elements of the array can be made equal using some operations.</p>
12
10
13
-
14
-
15
11
<p>Given an integer <code>n</code>, the length of the array. Return <em>the minimum number of operations</em> needed to make all the elements of arr equal.</p>
16
12
17
-
18
-
19
13
<p> </p>
20
14
21
15
<p><strong>Example 1:</strong></p>
22
16
23
-
24
-
25
17
<pre>
26
18
27
19
<strong>Input:</strong> n = 3
@@ -36,12 +28,8 @@ In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].
36
28
37
29
</pre>
38
30
39
-
40
-
41
31
<p><strong>Example 2:</strong></p>
42
32
43
-
44
-
45
33
<pre>
46
34
47
35
<strong>Input:</strong> n = 6
@@ -50,14 +38,10 @@ In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].
50
38
51
39
</pre>
52
40
53
-
54
-
55
41
<p> </p>
56
42
57
43
<p><strong>Constraints:</strong></p>
58
44
59
-
60
-
61
45
<ul>
62
46
<li><code>1 <= n <= 10^4</code></li>
63
47
</ul>
@@ -69,13 +53,51 @@ In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].
69
53
### **Python3**
70
54
71
55
```python
72
-
56
+
classSolution:
57
+
defminOperations(self, n: int) -> int:
58
+
ans =0
59
+
for i inrange(n >>1):
60
+
ans += (n - (2* i +1))
61
+
return ans
73
62
```
74
63
75
64
### **Java**
76
65
77
66
```java
67
+
classSolution {
68
+
publicintminOperations(intn) {
69
+
int ans =0;
70
+
for (int i =0; i < (n >>1); i++) {
71
+
ans += (n - (2* i +1));
72
+
}
73
+
return ans;
74
+
}
75
+
}
76
+
```
77
+
78
+
### **C++**
79
+
80
+
```cpp
81
+
classSolution {
82
+
public:
83
+
int minOperations(int n) {
84
+
int ans = 0;
85
+
for (int i = 0; i < (n >> 1); ++i) ans += (n - (2 * i + 1));
0 commit comments