Minimum Operations to Make All Array Elements Equal

You are given an array nums consisting of positive integers.

You are also given an integer array queries of size m. For the i^th query, you want to make all of the elements of nums equal to queries[i]. You can perform the following operation on the array any number of times:

  • Increase or decrease an element of the array by 1.

Return an array answer of size m where answer[i] is the minimum number of operations to make all elements of nums equal to queries[i].

Note that after each query the array is reset to its original state.

Example 1
Inputnums = [3,1,6,8], queries = [1,5]
Output[14,10]
For the first query, making all elements equal to 1 takes 2 + 5 + 7 = 14 operations, and for the second query, making all elements equal to 5 takes 2 + 4 + 1 + 3 = 10 operations.
Example 2
Inputnums = [2,9,6,3], queries = [10]
Output[20]
Increasing each value in the array to 10 takes 8 + 1 + 4 + 7 = 20 operations.

Constraints

  • n == nums.length
  • m == queries.length
  • 1 <= n, m <= 10^5
  • 1 <= nums[i], queries[i] <= 10^9

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate