1. Description
Given two integer arrays nums1 and nums2 of equal length n, minimize the sum of $(nums1[i] - nums2[i])^2$ over all indices.
Each operation increases or decreases one element by 1. You may perform up to k1 operations on nums1 and up to k2 operations on nums2.
Return the smallest achievable squared-difference sum. Modified elements may be negative, and unused operations are allowed.
2. Example
Example 1
Input: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0
Output: 579
Explanation: With no operations available, the result is $1^2 + 8^2 + 17^2 + 15^2 = 579$.
Example 2
Input: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1
Output: 43
Explanation: Increment nums1[0] and nums2[2]. The resulting absolute differences are [3,4,3,3], giving $9 + 16 + 9 + 9 = 43$.
3. Constraints
- n == nums1.length == nums2.length
- 1 <= n <= $10^5$
- 0 <= nums1[i], nums2[i] <= $10^5$
- 0 <= k1, k2 <= $10^9$
4. Solutions
Greedy with Counting Buckets
n = nums1.size(), U = 100001
Time complexity: O(n + U)
Space complexity: O(U)
| |