990. Minimum Operations to Make Subarray Elements Equal
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 nums by 1.
The task is to determine 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 = [5, -2, 3, 0, -5, 7], k = 3Â Â
Output: 5
Explanation:
Use 2 operations to increase nums[1] by 2, making the array [5, 0, 3, 0, -5, 7].
Use 3 operation to decrease nums[2] by 2, making the array [5, 0, 0, 0, -5, 7].
The array now contains a subarray [0, 0, 0].
The minimum operations required is 5.
Example 2:
Input: nums = [-1, -1, 4, 2, 3], k = 2Â Â
Output: 0
Explanation: The subarray [-1, -1] of size k = 2 already contains all equal elements, so no operations are needed.
Now Your Turn!
Pick the correct output for the given inputInput: nums = [3, 5, -2, 1, 4, 0, 6], k = 4Â
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 2 ≤ nums.length ≤ 105
- -106 ≤ nums[i] ≤ 106
- 2 ≤ k ≤ nums.length