Problem
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
nums
by 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
|
|
Example 2
|
|
Constraints
2 <= nums.length <= 10^5
-10^6 <= nums[i] <= 10^6
2 <= x <= nums.length
1 <= k <= 15
2 <= k * x <= nums.length
Examples
Solution
Method 1 – Sliding Window & Greedy (Heap)
Intuition
For each subarray of size x, the minimum operations to make all elements equal is to make them all equal to the median of the subarray. We need to select k non-overlapping subarrays with the lowest total cost.
Approach
- For every window of size x, calculate the cost to make all elements equal to its median.
- Use a heap to keep track of the k lowest costs among non-overlapping windows.
- Use dynamic programming to select k non-overlapping windows with minimum total cost.
- Edge case: If k * x > n, it’s impossible.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n * x * k)
— For each window, we sort and compute cost, and DP for k subarrays. - 🧺 Space complexity:
O(n * k)
— DP table and costs array.