Find Minimum Operations to Make All Elements Divisible by Three

easy array math modulo

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.

Inputnums = [1, 2, 3, 4]
Output3
1→0 (−1), 2→3 (+1), 3 already divisible, 4→3 (−1): total 3 operations.

def 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;
}
Time: O(n) Space: O(1)