Make Array Elements Equal Problem Statement

Given an integer array, your objective is to change all elements to the same value, minimizing the cost. The cost of changing an element from x to y is defined as |x - y|. Determine the minimum possible cost to achieve this goal.

Example:

Input:
ARR = [3, 4, 5]
Output:
2
Explanation:

If we convert all elements to the value 4, the cost for changing 3 to 4 is |3 - 4| which is 1, and changing 5 to 4 is |5 - 4| which is 1. Total cost is 1 + 1 = 2, which is minimal.

Input:

The first line contains an integer ‘T’, the number of test cases. Each test case includes:
An integer ‘N’, the number of elements in the array.
A line with ‘N’ space-separated integers representing the array elements.

Output:

For each test case, output the minimum cost to make all elements of the array equal. Print each test case output on a new line.

Constraints:

  • 1 <= T <= 5
  • 1 <= N <= 10^5
  • 1 <= ARR[i] <= 10^8
  • Time limit: 1 second
AnswerBot
4mo

Find the minimum cost to make all elements of an array equal by changing them to a common value.

  • Calculate the median of the array and find the sum of absolute differences between each element and the ...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Publicis Sapient

Q. What are the SOLID principles?
Q. What are extension methods?
Q. What is the difference between a List and a Tuple?
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits