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
Input
nums = [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
Input
nums = [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