classSolution: defminSumSquareDiff(self, a: List[int], nums2: List[int], k1: int, k2: int) -> int: ans, k = 0, k1 + k2 for i inrange(len(a)): a[i] = abs(a[i] - nums2[i]) ans += a[i] * a[i] ifsum(a) <= k: return0# 所有 a[i] 均可为 0 a.sort(reverse=True) a.append(0) # 哨兵 for i, v inenumerate(a): ans -= v * v j = i + 1 c = j * (v - a[j]) if c < k: k -= c continue v -= k // j return ans + k % j * (v - 1) * (v - 1) + (j - k % j) * v * v
classSolution { publiclongminSumSquareDiff(int[] a, int[] nums2, int k1, int k2) { intn= a.length, k = k1 + k2; longans=0L, sum = 0L; for (vari=0; i < n; ++i) { a[i] = Math.abs(a[i] - nums2[i]); sum += a[i]; ans += (long) a[i] * a[i]; } if (sum <= k) return0; // 所有 a[i] 均可为 0 Arrays.sort(a); for (vari= n - 1; ; --i) { varm= n - i; longv= a[i], c = m * (v - (i > 0 ? a[i - 1] : 0)); ans -= v * v; if (c < k) { k -= c; continue; } v -= k / m; return ans + k % m * (v - 1) * (v - 1) + (m - k % m) * v * v; } } }
classSolution { public: longlongminSumSquareDiff(vector<int> &a, vector<int> &nums2, int k1, int k2){ int n = a.size(), k = k1 + k2; long ans = 0L, sum = 0L; for (int i = 0; i < n; ++i) { a[i] = abs(a[i] - nums2[i]); sum += a[i]; ans += (long) a[i] * a[i]; } if (sum <= k) return0; // 所有 a[i] 均可为 0 sort(a.begin(), a.end(), greater<int>()); a.push_back(0); // 哨兵 for (int i = 0;; ++i) { long j = i + 1, v = a[i], c = j * (v - a[j]); ans -= v * v; if (c < k) { k -= c; continue; } v -= k / j; return ans + k % j * (v - 1) * (v - 1) + (j - k % j) * v * v; } } };
funcminSumSquareDiff(a, nums2 []int, k1, k2 int)int64 { ans, sum := 0, 0 for i, v := range a { a[i] = abs(v - nums2[i]) sum += a[i] ans += a[i] * a[i] } k := k1 + k2 if sum <= k { return0// 所有 a[i] 均可为 0 } sort.Sort(sort.Reverse(sort.IntSlice(a))) a = append(a, 0) // 哨兵 for i, v := range a { i++ ans -= v * v if c := i * (v - a[i]); c < k { k -= c continue } v -= k / i ans += k%i*(v-1)*(v-1) + (i-k%i)*v*v break } returnint64(ans) }
funcabs(x int)int { if x < 0 { return -x }; return x }