Find Minimum Operations to Make All Elements Divisible by Three
Problem
You are given an integer array nums. In one operation you may add or subtract 1 from any element. Return the minimum number of operations needed to make every element divisible by 3.
Each element is independent. For a value x let r = x % 3. If r = 0 it already costs nothing; otherwise the nearest multiple of 3 is reached by going down r steps or up 3 − r steps, so the best cost is min(r, 3 − r) — which is always 0 or 1.
nums = [1, 2, 3, 4]3def minimumOperations(nums):
ops = 0 # running total of +1/-1 adjustments
for x in nums:
r = x % 3 # remainder of x modulo 3
ops += min(r, 3 - r) # cheaper of rounding down (r) or up (3 - r)
return ops
function minimumOperations(nums) {
let ops = 0; // running total of +1/-1 adjustments
for (const x of nums) {
const r = x % 3; // remainder of x modulo 3
ops += Math.min(r, 3 - r); // cheaper of rounding down (r) or up (3 - r)
}
return ops;
}
int minimumOperations(int[] nums) {
int ops = 0; // running total of +1/-1 adjustments
for (int x : nums) {
int r = x % 3; // remainder of x modulo 3
ops += Math.min(r, 3 - r); // cheaper of rounding down (r) or up (3 - r)
}
return ops;
}
int minimumOperations(vector<int>& nums) {
int ops = 0; // running total of +1/-1 adjustments
for (int x : nums) {
int r = x % 3; // remainder of x modulo 3
ops += min(r, 3 - r); // cheaper of rounding down (r) or up (3 - r)
}
return ops;
}
Explanation
Because each operation changes a single element by exactly 1, the elements never interact — the cheapest plan handles every number on its own and then adds the costs up.
For one value x, look at its remainder r = x % 3, which is 0, 1, or 2. If r = 0 the number is already a multiple of 3 and costs nothing. Otherwise we can walk down to the lower multiple in r steps, or up to the higher multiple in 3 − r steps.
So the cost of fixing x is min(r, 3 − r). When r = 1 that is min(1, 2) = 1; when r = 2 it is min(2, 1) = 1. In other words every non-divisible number needs exactly one operation, which matches the hint — the answer is simply the count of elements not already divisible by 3.
We loop once over nums, accumulate min(r, 3 − r) into ops, and return it.
Example: [1, 2, 3, 4] gives remainders 1, 2, 0, 1 with costs 1, 1, 0, 1, summing to 3.