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: 1
💡 Note: Only one subarray [10,12]. To make equal: target 11 needs |10-11|+|12-11| = 1+1 = 2 ops, target 10 needs |10-10|+|12-10| = 0+2 = 2 ops. Optimal target is median which gives 1 operation.

Constraints

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

Visualization

Tap to expand
Find Minimum Operations: nums=[4,2,5,3], k=34253Subarray 1: [4,2,5]253Subarray 2: [2,5,3]Subarray 1 → Target 4: |4-4|+|2-4|+|5-4| = 3 operationsSubarray 2 → Target 3: |2-3|+|5-3|+|3-3| = 4 operationsMinimum: 3 operations
Understanding the Visualization
1
Input
Array nums=[4,2,5,3] and k=3 (need subarray of size 3)
2
Process
Check each subarray of size k, find optimal target (median)
3
Output
Return minimum operations needed across all subarrays
Key Takeaway
🎯 Key Insight: The median of any subarray minimizes the total operations needed to make all elements equal
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