A rooftop solar farm has n panels mounted on a shared calibration rig. Panel i currently sits at tilt angle current[i] degrees and must end up at target angle target[i] degrees before sunrise. The rig has a single motor action available: a pulse, which picks two different panels i and j and simultaneously raises panel i's tilt by exactly k degrees while lowering panel j's tilt by exactly k degrees. k is fixed for the whole rig. Determine the minimum number of pulses needed to bring every panel exactly to its target tilt, or report that no sequence of pulses can do it.
Line 1: two integers n and k.
Line 2: n integers, current[0..n-1].
Line 3: n integers, target[0..n-1].
A single integer: the minimum number of pulses required, or -1 if the targets can never be reached.
1 <= n <= 2*10^50 <= k <= 10^9-10^9 <= current[i], target[i] <= 10^9n = 1 no pulse can ever be issued, since a pulse always touches two distinct panels.Example 1
Input
3 2 1 5 3 5 1 3
Expected
2
Explanation
Panel 0 needs +4, panel 1 needs -4, panel 2 needs 0, and k=2 so panel 0 needs two +2 pulses of surplus and panel 1 needs two -2 pulses of deficit. Pulse 1: raise panel 0 by 2 and lower panel 1 by 2, giving [3,3,3]. Pulse 2: raise panel 0 by 2 and lower panel 1 by 2 again, giving [5,1,3], which matches the target. Two pulses suffice and none fewer can work, so the answer is 2.
Example 2
Input
2 3 0 0 1 -1
Expected
-1
Explanation
Panel 0 needs a net change of +1 and panel 1 needs a net change of -1, but the motor only moves tilt in steps of k=3 degrees per pulse. Since 1 is not a multiple of 3, no combination of pulses can ever land panel 0 exactly on 1, so the targets are unreachable and the answer is -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →