You are given an array ‘ARR’ of length ‘N’ which is filled with the values such that ARR[i] = (2*i + 1). You have to perform operations on the ‘ARR’ to make all elements of the array equal. In one operation, you can choose two elements from the array ‘ARR’ say ‘i’ and ‘j’, and can increment the value of ‘ARR[i]’ by one and decrement the value of ‘ARR[j]’ by one.
You have to find the minimum number of operations to make all the elements of the array ‘ARR’ equal. It is guaranteed that all elements of the array can be made equal using some operations.
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains an integer ‘N’, denoting the length of the array.
Output format:
For each test case, print the minimum number of operations to make all the elements of the array equal.
Output for each test case is printed on a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 1000
1 <= N <= 10^9
Time Limit: 1 sec
2
1
3
0
2
For the first test case,
Initially, the array ‘ARR’ is [1]. Since the array has only a single element therefore it will require 0 operations to make all array elements equal. So the output is 0.
For the second test case,
Initially, the array ‘ARR’ is [1, 3, 5]. So in the first operation, we will increment element 1 by one and decrement element 5 by one and the updated array will look like [2, 3, 4].
Then we perform a second operation in which we will increment 2 by one and decrement element 4 by one and the updated array will look like [3, 3, 3]. So finally all the elements of the array become equal in 2 operations. So the output is 2.
2
6
5
9
6
All elements of the array will be equal to the average value of the array.
Algorithm:
O(N), where ‘N’ is the length of the array.
Constructing the array ARR will take O(N) time. And then traversing over half of the array will also takes O(N) time. Therefore, the overall time complexity will be O(N).
O(N), where ‘N’ is the length of the array.
Since we are constructing an array ARR, which takes O(N) space. So, overall space complexity will be O(N).