Problem Description
Given an array of positive integers, nums, and multiple query values provided in the queries array, for each query you must determine the minimum number of operations needed to make all array elements equal to the query value. In one operation, you can increase or decrease an individual element by 1. After processing each query, the nums array is reset to its original state.
Key Insights
- Sort the nums array to facilitate binary search.
- Precompute a prefix sum array for efficient range sum queries.
- For a given query (target value), use binary search to find the index where numbers become greater than the target.
- Compute operations as the sum of differences for elements less than the target and those greater than the target.
- Use the formula:
- For left part (elements ≤ target): operations = target * count - prefix sum.
- For right part (elements > target): operations = (prefix sum of right part) - target * (number of elements in right part).
Space and Time Complexity
Time Complexity: O(n log n + m log n)
Space Complexity: O(n)
Solution
We can solve the problem by first sorting the array and building a prefix sum array. For each query, we perform a binary search to split the array into two segments: elements less than or equal to the target and those greater than the target. Using the prefix sum, we calculate the cost to bring all elements in the left segment up to the target and the cost to bring all elements in the right segment down to the target. Summing these costs yields the minimum number of operations required for that query.
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java with line-by-line comments.