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
nums1up tok1times - You can modify elements in
nums2up tok2times
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
Understanding the Visualization
1
Calculate Initial Differences
Find |nums1[i] - nums2[i]| for each position
2
Binary Search on Max Difference
Find the smallest achievable maximum difference
3
Apply Greedy Reduction
Reduce largest differences first for maximum impact
Key Takeaway
๐ฏ Key Insight: The greedy approach works because reducing larger differences has a quadratically greater impact on the final sum than reducing smaller ones.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code