#3505

Minimum Operations to Make Elements Within K Subarrays Equal

Hard
ArrayHash TableMathDynamic ProgrammingSliding WindowHeap (Priority Queue)Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Utilize the sliding window technique to efficiently calculate the operations needed for each window of size x. The median minimizes the total operations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a sliding window of size x to calculate the median for each window.
  2. 2Step 2: For each window, compute the operations needed to make all elements equal to the median.
  3. 3Step 3: Track the minimum operations for at least k non-overlapping windows.
solution.py10 lines
1import numpy as np
2
3def min_operations(nums, x, k):
4    n = len(nums)
5    ops = []
6    for i in range(n - x + 1):
7        median = int(np.median(nums[i:i+x]))
8        ops.append(sum(abs(nums[j] - median) for j in range(i, i + x)))
9    ops.sort()
10    return sum(ops[:k])

Complexity note: Sorting each window takes O(x log x) and we do this for n-x+1 windows, leading to O(n log n).

  • 1Using the median minimizes operations for equalizing numbers.
  • 2Sliding windows allow efficient calculation of overlapping subarrays.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.