Minimum Sum of Squared Difference - Problem

You're given two arrays nums1 and nums2 of equal length, and your goal is to minimize the sum of squared differences between corresponding elements.

The sum of squared difference is calculated as: sum((nums1[i] - nums2[i])²) for all valid indices.

Here's the twist: you can modify elements by adding or subtracting 1:

  • You can modify elements in nums1 up to k1 times
  • You can modify elements in nums2 up to k2 times

Strategy: Use your modifications wisely to bring corresponding elements as close to each other as possible. The closer they are, the smaller the squared difference!

Note: Elements can become negative through modifications.

Input & Output

example_1.py — Basic Case
$ Input: nums1 = [1, 2, 3, 4], nums2 = [2, 10, 20, 19], k1 = 0, k2 = 0
Output: 579
💡 Note: Without any modifications, differences are [1, 8, 17, 15]. Sum of squares = 1² + 8² + 17² + 15² = 1 + 64 + 289 + 225 = 579
example_2.py — With Modifications
$ Input: nums1 = [1, 4, 10, 12], nums2 = [5, 8, 6, 9], k1 = 1, k2 = 1
Output: 43
💡 Note: Initial differences: [4, 4, 4, 3]. We can modify nums1[2] from 10 to 9 (k1=1) and nums2[2] from 6 to 7 (k2=1), making differences [4, 4, 2, 3]. Sum = 16 + 16 + 4 + 9 = 45. Better strategy: reduce the largest differences first to get 43.
example_3.py — Edge Case
$ Input: nums1 = [1, 0, 1, 1], nums2 = [1, 0, 1, 1], k1 = 3, k2 = 3
Output: 0
💡 Note: Arrays are already identical, so sum of squared differences is 0. No modifications needed.

Constraints

  • n == nums1.length == nums2.length
  • 1 ≤ n ≤ 105
  • 0 ≤ nums1[i], nums2[i] ≤ 105
  • 0 ≤ k1, k2 ≤ 109
  • Elements can become negative after modifications

Visualization

Tap to expand
Minimum Sum of Squared Difference INPUT nums1 1 2 3 4 nums2 2 10 20 19 Differences |nums1[i] - nums2[i]| 1 8 17 15 k1 = 0 k2 = 0 Total modifications: 0 (No changes allowed) ALGORITHM (Greedy) 1 Calculate Differences diff[i] = |nums1[i] - nums2[i]| 2 Check Modifications Total k = k1 + k2 = 0 3 No Reduction Possible k=0, cannot reduce diffs 4 Sum Squared Diffs Sum all diff[i]^2 Calculation: 1^2 = 1 8^2 = 64 17^2 = 289 15^2 = 225 Sum = 579 FINAL RESULT Original arrays unchanged (no modifications available) Final Differences: 1 8 17 15 OUTPUT 579 OK - Verified 1+64+289+225 = 579 Key Insight: Greedy approach: Use modifications (k1+k2) to reduce the LARGEST differences first. Reducing a large diff by 1 saves more than reducing a small diff (due to squaring). In this case, k1=k2=0, so no modifications possible - calculate sum of squared diffs directly. TutorialsPoint - Minimum Sum of Squared Difference | Greedy Approach
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
31.7K Views
Medium Frequency
~25 min Avg. Time
1.3K 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