You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n.
The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i])2 for each 0 <= i < n.
You are also given two positive integers k1 and k2. You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times.
Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times.
Note: You are allowed to modify the array elements to become negative integers.
Example 1:
Input: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0
Output: 579
Explanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0.
The sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2 = 579.
Example 2:
Input: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1
Output: 43
Explanation: One way to obtain the minimum sum of square difference is:
- Increase nums1[0] once.
- Increase nums2[2] once.
The minimum of the sum of square difference will be:
(2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2 = 43.
Note that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.
Constraints:
- n == nums1.length == nums2.length
- 1 <= n <= 105
- 0 <= nums1[i], nums2[i] <= 105
- 0 <= k1, k2 <= 109
我相信用 binary search 来找最后的那个最大的 difference 应该会更快, 但是一写到处理无法整体减除的情况(所剩的 k 只够调整部分当前最大 differences 的情况)就彻底乱了, 所以干脆用最简单的办法来解决, 还好, 题目的测试没有那么严格, 没有报超时。
首先明确一点, k1 和 k2 在功能上是没有区别的, 就是调整 nums1[i] - nums2[i]的值。我们首先把所有的 nums1[i]-nums2[i]收集起来, 并且进行排序, 这就是所有的 differneces, 但是我们为了速度快一些, 我们把相同的 differences 合并起来,并记录其数量, 形成(diff, count)的形式。收集完之后我们从最大的 difference 开始(因为减除相同的数量, 越大的 difference 减少的最终平方值越多, 在我们看来也就是收益越大), 每次 difference 减少 1, 整体减少 count, 也就是我们消耗 count 个 k 值来降低 difference, 如果剩余的 k 值足够这次减除, 我们就把当前 difference 减 1 再放回数组里, 之所以要走这一步,一是为了简单我们最终还是用 diffs 这个数组来计算答案, 二是我们将 difference-1 后可能与下一个 difference 的值相同, 如果相同的话我们要合并这两个,然后再放到数组中。如果剩余的 k 值不够, 那我们就将部分当前 difference-1, 将减除的这部分和未减除的部分都放回数组中,然后跳出遍历,计算最终的答案。
use std::collections::HashMap;
impl Solution

最低0.47元/天 解锁文章
1426

被折叠的 条评论
为什么被折叠?



