Minimum Operations To Make Array Equal
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.
Input format:
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.
Constraints:
1 <= T <= 1000
1 <= N <= 10^9
Time Limit: 1 sec
Follow Up:
Can you do this in constant time and space?
CodingNinjas
author
2y
Brute Force
- The idea behind this approach is we have to calculate the average of all the elements of the array ‘ARR’ because the sum of all elements of the array always remains constant.
- So calculating ...read more
CodingNinjas
author
2y
Using Cases
- It is the optimized version from the previous approach.
- In this approach, we have to consider two cases, i.e, if the length of the array is even or odd.
- If the length of the array is even the...read more
Help your peers!
Add answer anonymously...
Top Procol Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app