Problem
You are given an array nums
consisting of positive integers.
You are also given an integer array queries
of size m
. For the ith
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 arrayanswer
of sizem
whereanswer[i]
_is theminimum number of operations to make all elements of _nums
equal toqueries[i]
.
Note that after each query the array is reset to its original state.
Examples
Example 1
|
|
Example 2
|
|
Constraints
n == nums.length
m == queries.length
1 <= n, m <= 10^5
1 <= nums[i], queries[i] <= 10^9
Solution
Method 1 – Prefix Sum & Binary Search
Intuition
To make all elements equal to a target value, the minimum number of operations is the sum of absolute differences between each element and the target. By sorting the array and using prefix sums, we can efficiently answer each query.
Approach
- Sort nums and compute prefix sums.
- For each query, use binary search to find the position where query would be inserted.
- For elements less than query, total operations = query * count - sum of those elements.
- For elements greater than or equal to query, total operations = sum of those elements - query * count.
- Add both to get the answer for each query.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n + m log n)
— Sorting nums and prefix sum is O(n log n), each query is O(log n). - 🧺 Space complexity:
O(n)
— For prefix sum array and sorting.