Find the minimum number of element adjustments needed so the total sum becomes divisible by k.
You are given an integer array nums and an integer k.
In one operation, you may change the value of a single array element by 1 in either direction. Your goal is to make the sum of the array divisible by k using the fewest operations possible.
Return the minimum number of operations required.
Only the remainder of the total sum modulo k matters. Each +1 or -1 operation changes the sum by exactly one, so the answer is determined by how far the current sum is from the nearest multiple of k.
nums: an integer arrayk: a positive integerYou may assume the array can be modified by incrementing or decrementing individual elements by 1 per operation.
Return the minimum number of +1/-1 operations needed so that the sum of nums is divisible by k.
1 <= nums.lengthk > 0Example 1
Input
nums = [3, 1, 4, 2], k = 6
Output
0
Explanation
The sum is 10, and 10 mod 6 = 4. Since we can change one element by 2, or equivalently adjust the total by the needed amount, the minimum operations are determined by the remainder. In this illustrative version, if the task is to make the sum divisible by 6 by unit operations, the cheapest total adjustment is 2.
Example 2
Input
nums = [1, 2, 3], k = 4
Output
2
Explanation
The sum is 6, and 6 mod 4 = 2. Two -1 operations (for example, changing 3 -> 1) reduce the sum by 2, making it divisible by 4.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.