Find Minimum Operations to Make All Elements Divisible by Three
You are given an integer array nums. In one operation you can add 1 to or subtract 1 from any element. Return the minimum number of operations needed to make every element divisible by 3.
30:00
Find Minimum Operations to Make All Elements Divisible by Three
You are given an integer array nums. In one operation you can add 1 to or subtract 1 from any element. Return the minimum number of operations needed to make every element divisible by 3.
Example 1:
Input: {"nums":[1,2,3,4]}
Output: 3
Constraints:
1≤ nums.length ≤50
1≤ nums[i] ≤50
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"nums":[1,2,3,4]}
Every integer is at most one step from a multiple of 3: remainder 1 steps down, remainder 2 steps up, remainder 0 is already done.
nums and the nudge each one needs
1
2
3
4
✓ remainder 0
−1 remainder 1
+1 remainder 2
where it sits between multiples of 3
Multiples of 3 are spaced 3 apart, so any number has one within distance 1.