The title
There exists an array arr of length n, where arr[I] = (2 * I) + 1 (0 <= I < n).
In one operation, you can pick two subscripts, call them x and y (0 <= x, y < n) and make arr[x] minus 1, arr[y] plus 1 (i.e. Arr [x] -=1 and arr[y] += 1). The ultimate goal is to make all elements in the array equal. The problem test case will ensure that, after several steps, all elements in the array will eventually be equal.
I give you an integer n, the length of the array. Return the minimum operand required to make all elements in array ARR equal.
Example 1: Input: n = 3 Output: 2 Arr = [1, 3, 5] The first operation selects x = 2 and y = 0, making the array [2, 3, 4] the second operation continues to select x = 2 and y = 0, which will make the array [3, 3, 3] example 2: Input: n = 6 Output: 9Copy the code
Tip:
1 <= n <= 10^4
Their thinking
class Solution:
def minOperations(self, n: int) -> int:
average = n
maxNum = (n-1)*2+1
res = 0
# print(average, maxNum)
while maxNum > average:
res += maxNum - average
maxNum -= 2
return res
if __name__ == '__main__':
n = 6
ret = Solution().minOperations(n)
print(ret)
Copy the code