LeetCode Problem - Link

Problem

You are given an integer array nums. In one operation, you can add or subtract 1 from any element of nums.

Return the minimum number of operations to make all elements of nums divisible by 3.

 

Example 1:

Input: nums = [1,2,3,4]

Output: 3

Explanation:

All array elements can be made divisible by 3 using 3 operations:

  • Subtract 1 from 1.
  • Add 1 to 2.
  • Subtract 1 from 4.



Sequential Approach

First, we need to check if the array item is divisible by 3, if yes ignore. If no, add one to it and minus one to it, check if either of these are divisible by 3. If either are divisible, increase the counter.


/**
 * @param {number[]} nums
 * @return {number}
 */
var minimumOperations = function(nums) {
    let count = 0;
    for(var i=0;i<nums.length;i++){
        let isDivBy3 = nums[i] % 3 ===0


        if(!isDivBy3){
            let plusOne = nums[i] + 1
            let minusOne = nums[i] - 1


            if(plusOne%3!=0 || minusOne%3!=0){
                count+=1
            }
        }
    }
    return count;
};