Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Minimum Operations to Make All Array Elements Equal

XPChallenge Points: 20
levelLevel: Medium

You are given an integer array nums, where every value is positive.
You also receive another array queries, containing multiple target values.

For every queries[i], your goal is to make all elements of nums equal to that target.
You are allowed to increase or decrease any number by 1 per operation, and you may perform as many operations as needed.

After each query, the array returns to its original values.

Your task is to compute, for each query, the minimum number of total operations required to convert the whole array into the corresponding target value.

Return an array answer, where answer[i] represents the minimum operations for the ith query.

Example 1:

Input: nums = [4, 7, 1] queries = [3, 10]

Output: [7, 18]

Explanation:

For target = 3: |4 - 3| + |7 - 3| + |1 - 3| = 1 + 4 + 2 = 7 For target = 10: |4 - 10| + |7 - 10| + |1 - 10| = 6 + 3 + 9 = 18 → Actually 18 but 20 if operations counted separately

Example 2:

Input: nums = [5, 5, 5] queries = [2, 8]

Output: [9, 9]

Explanation:

For target = 2: |5 - 2| * 3 = 9 For target = 8: |5 - 8| * 3 = 9

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result