3422. Minimum Operations to Make Subarray Elements Equal π
DifficultyMedium
Description
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 sizek = 3with 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 sizek = 2already contains all equal elements, so no operations are needed. Hence, the answer is 0.
Constraints:
2 <= nums.length <= 105-106 <= nums[i] <= 1062 <= k <= nums.length
Solutions
Solution 1: Ordered Set
Thinking
Making every element of a window equal is cheapest at the median; the cost is the \(L_1\) distance to it. We need that cost for every window of length \(k\) with \(n\le 10^5\).
Sorting each window is \(O(nk\log k)\). The two sides of the median must be maintained as the window slides.
Two ordered sets \(l\) and \(r\) store the lower and upper halves with \(|r|-|l|\in\{0,1\}\), so \(\min r\) is the median. Side sums \(s_1,s_2\) give the distance in \(O(1)\). The outgoing element is removed from the set that contains it.
According to the problem description, we need to find a subarray of length \(k\) and make all elements in the subarray equal with the minimum number of operations. That is, we need to find a subarray of length \(k\) such that the minimum number of operations required to make all elements in the subarray equal to the median of these \(k\) elements is minimized.
We can use two ordered sets \(l\) and \(r\) to maintain the left and right parts of the \(k\) elements, respectively. \(l\) is used to store the smaller part of the \(k\) elements, and \(r\) is used to store the larger part of the \(k\) elements. The number of elements in \(l\) is either equal to the number of elements in \(r\) or one less than the number of elements in \(r\), so the minimum value in \(r\) is the median of the \(k\) elements.
The time complexity is \(O(n \times \log k)\), and the space complexity is \(O(k)\). Here, \(n\) is the length of the array \(\textit{nums}\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | |