Make Array Elements Equal
You are given an array of integers of size ‘N’. You have to make the elements of the array equal, and the cost of changing the element ‘x’ to ‘y’ is abs(x -y). Your task is to find the minimum cost to make the elements of the array equal.
For example:
Consider ARR = [3, 4, 5] now suppose if we want to change every element value to 4, then the cost of changing 3 to 4 is |3 - 4| which is 1, and the cost of changing 5 to 4 is |5 - 4| which is 1, so the total cost is 1 + 1 = 2. The value 2 is the minimum cost to make all values in the array equal. Hence, the answer is 2.
Input Format:
The first line of the input contains an integer ‘T’ denoting the number of test cases.
The first line of each test case contains a single integer, ‘N’, denoting the number of elements in the array.
The second line of each test case contains 'N' space-separated integers denoting the elements of the array.
Output Format:
For each test case, print the minimum cost to make elements of the array equal.
Print the output of each test case in a separate line.
Constraints:
1 <= T <= 5
1 <= N <= 10^5
1 <= ARR[i] <= 10^8
Time limit: 1 sec
CodingNinjas
author
2y
Approach :
1) We will initialize the variable lowerLimit and upperLimit with the minimum and maximum value present in the array.
2) Iterate while upperLimit - lowerLimit is more than 2.
2.1) Set the vari...read more
CodingNinjas
author
2y
Brute Force
In this approach, we will traverse the array for each value between the minimum and maximum value of the array. We will find the cost for each value to make the elements of the array equal ...read more
CodingNinjas
author
2y
Binary Search
In this one pattern, as we increase the target value, the cost decreases up to a limit then starts increasing, which means some U shape graph is present. We have to find the lowest cost, ...read more
Add answer anonymously...
Top Publicis Sapient Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in Publicis Sapient Software Developer
>
Publicis Sapient Software Developer Interview Questions
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