Minimum Operations to Make Elements Within K Subarrays Equal Problem
Description
LeetCode Problem 3505.
You are given an integer array nums and two integers, x and k. You can perform the following operation any number of times (including zero):
- Increase or decrease any element of
numsby 1.
Return the minimum number of operations needed to have at least k non-overlapping subarrays of size exactly x in nums, where all elements within each subarray are equal.
Example 1:
Input: nums = [5,-2,1,3,7,3,6,4,-1], x = 3, k = 2
Output: 8
Explanation:
- Use 3 operations to add 3 to nums[1] and use 2 operations to subtract 2 from nums[3]. The resulting array is [5, 1, 1, 1, 7, 3, 6, 4, -1].
- Use 1 operation to add 1 to nums[5] and use 2 operations to subtract 2 from nums[6]. The resulting array is [5, 1, 1, 1, 7, 4, 4, 4, -1].
- Now, all elements within each subarray [1, 1, 1] (from indices 1 to 3) and [4, 4, 4] (from indices 5 to 7) are equal. Since 8 total operations were used, 8 is the output.
Example 2:
Input: nums = [9,-2,-2,-2,1,5], x = 2, k = 2
Output: 3
Explanation:
- Use 3 operations to subtract 3 from nums[4]. The resulting array is [9, -2, -2, -2, -2, 5].
- Now, all elements within each subarray [-2, -2] (from indices 1 to 2) and [-2, -2] (from indices 3 to 4) are equal. Since 3 operations were used, 3 is the output.
Constraints:
2 <= nums.length <= 10^5-10^6 <= nums[i] <= 10^62 <= x <= nums.length1 <= k <= 152 <= k * x <= nums.length
Solution
Approach: Window Medians + Dynamic Programming
Making all elements of a window equal costs the least when they all become the window's median. So the plan has two parts: the cost of every window of length x, then a DP that picks k non-overlapping windows.
Window costs. Compress the values and keep two Fenwick trees over them while the window slides: one counts the elements per value, the other sums them. The median is the ceil(x / 2)-th smallest element, found by walking down the tree. If c and s are the count and sum of the elements smaller than the median med, and total is the window sum, the cost is med * c - s + (total - s) - med * (x - c).
DP. Let f[i][j] be the minimum cost of choosing j non-overlapping windows inside the first i elements. Either element i is not the end of a chosen window, or the window ending at i is the last one:
f[i][j] = min(f[i - 1][j], f[i - x][j - 1] + cost[i])
with f[i][0] = 0 and everything else infinite at the start. The answer is f[n][k].
Complexity: time O(n log n + n * k), space O(n * k).
class Solution:
def minOperations(self, nums: List[int], x: int, k: int) -> int:
n = len(nums)
vals = sorted(set(nums))
rank = {v: i + 1 for i, v in enumerate(vals)}
m = len(vals)
cnt = [0] * (m + 1) # Fenwick tree: how many window elements per value
tot = [0] * (m + 1) # Fenwick tree: sum of window elements per value
top = m.bit_length()
def update(i: int, dc: int, dv: int) -> None:
while i <= m:
cnt[i] += dc
tot[i] += dv
i += i & -i
# cost[i]: operations to make the window nums[i - x + 1..i] equal (all go to the median)
cost = [0] * n
window = 0
need = (x + 1) // 2
for i in range(n):
update(rank[nums[i]], 1, nums[i])
window += nums[i]
if i >= x:
update(rank[nums[i - x]], -1, -nums[i - x])
window -= nums[i - x]
if i >= x - 1:
# descend the tree to the need-th smallest value
p = c = s = 0
for b in range(top, -1, -1):
q = p + (1 << b)
if q <= m and c + cnt[q] < need:
p = q
c += cnt[q]
s += tot[q]
med = vals[p]
cost[i] = med * c - s + (window - s) - med * (x - c)
INF = 1 << 60
f = [[INF] * (k + 1) for _ in range(n + 1)]
for i in range(n + 1):
f[i][0] = 0
for i in range(1, n + 1):
for j in range(1, k + 1):
f[i][j] = f[i - 1][j]
if i >= x and f[i - x][j - 1] < INF:
f[i][j] = min(f[i][j], f[i - x][j - 1] + cost[i - 1])
return f[n][k]