Two arrays, k1 + k2 single-step nudges, and one squared bill — spend every nudge where the gap is biggest.
Pool k1 + k2 into a single budget and spend every move on the current largest gap.
Only the gaps d = |nums1[i] − nums2[i]| matter — never which array you nudge, since +1 here and −1 there shrink the same gap. Shrinking a gap from d to d−1 cuts the bill by d² − (d−1)² = 2d−1, which grows with d. So the single most valuable move is always on the current maximum, and the whole problem becomes draining a pile of gaps from the top.
Each frame drains one gap level exactly like the Counter loop below: whole levels fall at once, a short budget takes a partial bite, and the Σd² readout ticks down to the answer. Enter any two equal-length arrays plus the pooled budget k.
class Solution:
def minSumSquareDiff(self, nums1, nums2, k1, k2):
from collections import Counter
k = k1 + k2 # one shared budget: +1 here == -1 there
diffs = [abs(a - b) for a, b in zip(nums1, nums2)]
total = sum(diffs)
if k >= total:
return (k - total) % 2 # leftovers bounce 0 -> 1 -> 0 ...
freq = Counter(diffs)
for d in range(max(diffs), 0, -1): # drain from the top
c = freq[d]
if not c:
continue
t = min(c, k) # whole level, or one partial bite
freq[d] -= t
freq[d - 1] += t
k -= t
if k == 0:
break
return sum(d * d * c for d, c in freq.items())
The trace above runs this same loop: whole-level drops, at most one partial bite, and the parity shortcut for leftover moves.
k ≥ sum(diffs) → (k − sum) % 2Spare moves can't push below zero, so each extra move flips one gap 0→1→0…; an odd leftover strands a single 1.t = min(count, k)A level either falls intact or absorbs the final moves. There is never a reason to skip a level and shave a smaller gap instead.saving = 2d − 1Shrinking d to d−1 earns 2d−1, so the top level always pays best. That formula is the whole exchange argument in one line.No moves to spend, so the bill is just 1 + 64 + 289 + 225. The trace is two frames: start, done — greediness needs no moves to be correct.
Gaps start [4,4,4,3]; both moves bite level 4, leaving [4,3,3,3] for 16 + 9+9+9 = 43. Any other placement of the same two moves scores worse — try it in the trace.
I pool both operation counts into one budget since only the absolute gaps matter, then repeatedly shave the current largest gap — each unit there saves the most — draining level by level with a frequency table, and if moves outlast the total gap the answer is just the leftover parity.