Minimum Operations to Make Subarray Elements Equal - Problem

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 nums by 1.

Return the minimum number of operations required to ensure that at least one subarray of size k in nums has all elements equal.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,2,5,3], k = 3
Output: 3
💡 Note: Subarray [4,2,5]: make all equal to 4 → |4-4|+|2-4|+|5-4| = 0+2+1 = 3 operations. Subarray [2,5,3]: make all equal to 3 → |2-3|+|5-3|+|3-3| = 1+2+0 = 3 operations. Minimum is 3.
Example 2 — All Same Elements
$ Input: nums = [1,1,1,1], k = 2
Output: 0
💡 Note: Any subarray of size 2 already has all elements equal (both are 1), so 0 operations needed.
Example 3 — Minimum Size
$ Input: nums = [10,12], k = 2
Output: 2
💡 Note: Only one subarray [10,12]. Using median approach: sorted = [10,12], median = 12, operations = |10-12|+|12-12| = 2+0 = 2.

Constraints

  • 2 ≤ nums.length ≤ 105
  • 1 ≤ k ≤ nums.length
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Minimum Operations to Make Subarray Elements Equal INPUT nums array: 4 i=0 2 i=1 5 i=2 3 i=3 k = 3 Possible subarrays of size 3: [4, 2, 5] indices 0-2 [2, 5, 3] indices 1-3 Goal: Make one subarray have all equal elements ALGORITHM STEPS 1 Sliding Window Check each k-sized window 2 Find Median Median minimizes total ops 3 Calculate Cost Sum |elem - median| for each 4 Track Minimum Return smallest cost Cost Calculation: Window [4,2,5]: median=4 |4-4|+|2-4|+|5-4|=0+2+1=3 Window [2,5,3]: median=3 |2-3|+|5-3|+|3-3|=1+2+0=3 min(3, 3) = 3 FINAL RESULT Optimal subarray choice: 4 2 5 3 Transform to median (4): 4 4 4 3 Operations needed: 4 --> 4: 0 ops 2 --> 4: 2 ops (+2) 5 --> 4: 1 op (-1) Output: 3 OK - Minimum ops found! Key Insight: The median minimizes the sum of absolute deviations. For a subarray of size k, converting all elements to the median value requires the minimum number of increment/decrement operations. Time complexity: O(n*k) naive, O(n log k) with sorted containers/heaps for larger inputs. TutorialsPoint - Minimum Operations to Make Subarray Elements Equal | Optimal Solution
Asked in
Google 25 Microsoft 20 Amazon 15
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen