[
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, 17
to see the pattern. Then we need to make all numbers equal to9
. How many operations we need? For pair7,11
we need2
operations, for5,13
we need4
operation, then6
and8
. In total we need2+4+6+8 = 20
operations. 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, 15
to see the pattern. Then we need to make all numbers equal to8
. We need1 + 3+ 5 + 7 = 16
operations and in general case we need1 + 3 + ... + 2k-1 = k*k = n*n//4
operations. - 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