#2333

Minimum Sum of Squared Difference

Medium
ArrayBinary SearchGreedySortingHeap (Priority Queue)GreedyHeap (Priority Queue)Sorting
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)

The optimal solution leverages a greedy approach, where we focus on reducing the largest differences first. By using the available modifications efficiently, we can minimize the sum of squared differences significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the initial differences between nums1 and nums2.
  2. 2Step 2: Use a max-heap (or priority queue) to store the absolute differences.
  3. 3Step 3: While we have modifications left (k1 + k2), pop the largest difference from the heap, reduce it by 1, and push it back into the heap.
  4. 4Step 4: After all modifications, calculate the final sum of squared differences.
solution.py17 lines
1# Full working Python code
2import heapq
3
4def minSumSquaredDiff(nums1, nums2, k1, k2):
5    n = len(nums1)
6    diffs = []
7    for i in range(n):
8        diffs.append(abs(nums1[i] - nums2[i]))
9    heapq._heapify_max(diffs)
10    total_mods = k1 + k2
11    while total_mods > 0:
12        max_diff = heapq._heappop_max(diffs)
13        max_diff -= 1
14        heapq._heapify_max(diffs)
15        heapq.heappush(diffs, max_diff)
16        total_mods -= 1
17    return sum(d ** 2 for d in diffs)

Complexity note: The complexity arises from sorting the differences and maintaining the heap structure for modifications.

  • 1Modifying the largest differences first is crucial for minimizing the squared differences.
  • 2The total number of modifications (k1 + k2) can be treated as a single resource to optimize the differences.

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