Minimum Operations to Make All Array Elements Equal - Problem
You're given an array nums of positive integers and multiple queries. For each query, you need to determine the minimum number of operations to make all elements in the array equal to a target value.
The only operation allowed is to increase or decrease any element by exactly 1. After each query, the array resets to its original state.
Goal: For each query value, calculate the total cost to transform all array elements to that value.
Example: If nums = [2, 7, 4] and query is 5, you need |2-5| + |7-5| + |4-5| = 3 + 2 + 1 = 6 operations.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [3,1,6,8], queries = [1,5]
โบ
Output:
[14,10]
๐ก Note:
For query 1: |3-1| + |1-1| + |6-1| + |8-1| = 2+0+5+7 = 14. For query 5: |3-5| + |1-5| + |6-5| + |8-5| = 2+4+1+3 = 10
example_2.py โ Single Element
$
Input:
nums = [2], queries = [3,1,2]
โบ
Output:
[1,1,0]
๐ก Note:
For query 3: |2-3| = 1. For query 1: |2-1| = 1. For query 2: |2-2| = 0
example_3.py โ Large Values
$
Input:
nums = [1,1000000], queries = [500000]
โบ
Output:
[999999]
๐ก Note:
For query 500000: |1-500000| + |1000000-500000| = 499999 + 500000 = 999999
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i], queries[j] โค 106
- 1 โค queries.length โค 105
- All values are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Sort Plants
Arrange plants by current height: [1, 2, 4, 7]
2
Find Split Point
Use binary search to find where target height (5) would go
3
Calculate Adjustments
Plants below target need raising, plants above need lowering
4
Use Prefix Sums
Quickly calculate total adjustments using mathematical formulas
Key Takeaway
๐ฏ Key Insight: Sort once, then use binary search + prefix sums to answer each query in O(log n) time
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code