Given an array, find the minimum number of element changes needed so every value becomes divisible by 3.
Problem
You are given an integer array nums. In one operation, you may choose an element and change it by +1 or -1.
Return the minimum number of operations required so that every element in the array becomes divisible by 3.
Because each operation changes a value by exactly one, the cost to make a number divisible by 3 depends only on its remainder when divided by 3.
Clarification
- You may apply operations to any elements, in any order.
- The goal is to minimize the total number of
+1/-1steps across the entire array.
Input Format
- A single integer array
nums.
Output Format
- Return an integer: the minimum total number of operations needed.
Constraints
1 <= nums.length <= $10^{5}$0 <= nums[i] <= $10^{9}$
Notes
- Numbers already divisible by
3need no changes. - A number with remainder
1can be fixed in one step. - A number with remainder
2can also be fixed in one step by decreasing it by1, or in two steps by increasing it to the next multiple of3depending on the allowed move strategy; choose the minimum per element.
Input Format
nums: integer array
Output Format
- Return the minimum number of
+1/-1operations required so that all elements are divisible by3.
Constraints
1 <= nums.length <= $10^{5}$0 <= nums[i] <= $10^{9}$
Example 1
Input
nums = [3, 6, 1, 2]
Output
2
Explanation
3 and 6 are already divisible by 3. 1 needs one -1 operation, and 2 needs one -1 operation. Total = 2.
Example 2
Input
nums = [4, 7, 10]
Output
3
Explanation
Each value leaves remainder 1 when divided by 3, so each needs one operation to become divisible by 3. Total = 3.
Premium problem context
Unlock deeper context for this problem
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.