Minimum Operations to Make Subarray Elements Equal Problem
Description
LeetCode Problem 3422.
You are given an integer array nums and an integer k. You can perform the following operation any number of times:
- Increase or decrease any element of
numsby 1.
Return the minimum number of operations required to ensure that at least one subarray of size k in nums has all elements equal.
Example 1:
Input: nums = [4,-3,2,1,-4,6], k = 3
Output: 5
Explanation:
- Use 4 operations to add 4 to nums[1]. The resulting array is [4, 1, 2, 1, -4, 6].
- Use 1 operation to subtract 1 from nums[2]. The resulting array is [4, 1, 1, 1, -4, 6].
- The array now contains a subarray [1, 1, 1] of size k = 3 with all elements equal. Hence, the answer is 5.
Example 2:
Input: nums = [-2,-2,3,1,4], k = 2
Output: 0
Explanation:
- The subarray [-2, -2] of size k = 2 already contains all equal elements, so no operations are needed. Hence, the answer is 0.
Constraints:
2 <= nums.length <= 10^5-10^6 <= nums[i] <= 10^62 <= k <= nums.length
Solution
Approach: Sliding Window + Fenwick Tree
To make all elements of a window equal at the lowest cost, move every element to the window's median; the cost is the sum of the distances to it. So we compute that cost for each of the n - k + 1 windows of size k and take the minimum.
Keep two Fenwick trees over the compressed values, one counting how many window elements have each value and one summing them. For a window:
- Walk down the count tree to find the median, the
ceil(k / 2)-th smallest valuemed. The same walk givesc, the number of elements smaller thanmed, ands, their sum. - With
totalthe sum of the window, the cost ismed * c - sfor the smaller elements plus(total - s) - med * (k - c)for the rest.
Sliding the window by one adds the new element and removes the old one in the two trees.
Complexity: O(n log n) time and O(n) space.
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
vals = sorted(set(nums))
m = len(vals)
rank = {v: i + 1 for i, v in enumerate(vals)}
cnt = [0] * (m + 1) # Fenwick tree: how many window elements per value
sm = [0] * (m + 1) # Fenwick tree: their sums
top = 1
while top * 2 <= m:
top *= 2
need = (k + 1) // 2
total = 0
ans = 1 << 62
for i, x in enumerate(nums):
j = rank[x]
while j <= m:
cnt[j] += 1
sm[j] += x
j += j & -j
total += x
if i >= k:
y = nums[i - k]
j = rank[y]
while j <= m:
cnt[j] -= 1
sm[j] -= y
j += j & -j
total -= y
if i >= k - 1:
# walk down the tree to the median (the need-th smallest value)
pos, rem, c, s, step = 0, need, 0, 0, top
while step:
nxt = pos + step
if nxt <= m and cnt[nxt] < rem:
pos = nxt
rem -= cnt[nxt]
c += cnt[nxt]
s += sm[nxt]
step >>= 1
med = vals[pos]
ans = min(ans, med * c - s + (total - s) - med * (k - c))
return ans