[
math
]
Leetcode 1551. Minimum Operations to Make Array Equal
Problem statement
https://leetcode.com/problems/minimum-operations-to-make-array-equal/
Solution
All we need to do in this problem is to use some school math. There will be two cases we need to consider, odd and even n. Let us consider odd case first:
- Odd case: consider
1, 3, 5, 7, 9, 11, 13, 15, 17to see the pattern. Then we need to make all numbers equal to9. How many operations we need? For pair7,11we need2operations, for5,13we need4operation, then6and8. In total we need2+4+6+8 = 20operations. How to calculate it in general case? Ifn = 2k + 1, then we need to calculate2 + 4 + ... + 2k, which is the sum of arithmetic progression and equal tok*(k+1) = (n*n-1)//4. - Even case: consider
1, 3, 5, 7, 9, 11, 13, 15to see the pattern. Then we need to make all numbers equal to8. We need1 + 3+ 5 + 7 = 16operations and in general case we need1 + 3 + ... + 2k-1 = k*k = n*n//4operations. - Finally we can write down it as one formula, using rounding.
Complexity
Time and space complexity is just O(1)
Code
class Solution:
def minOperations(self, n):
return n*n//4