DEV Community

Cover image for Leetcode — 3190. Find Minimum Operations to Make All Elements Divisible by Three
Ben Pereira
Ben Pereira

Posted on

Leetcode — 3190. Find Minimum Operations to Make All Elements Divisible by Three

This is an easy problem with description being:

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.

Example 2:

Input: nums = [3,6,9]

Output: 0

Constraints:

1 <= nums.length <= 50

1 <= nums[i] <= 50

Looking into the problem and thinking about number 3, if a number is divided by 3 and there is no fraction, it means no add/subtract is needed. But if fraction remains it means that you can either add or subtract that you will get into a number that has no fraction.

With that in mind, a simple loop and a check is enough to get this done:

class Solution {
    public int minimumOperations(int[] nums) {
        int sum=0;
        for(int i=0;i<nums.length;i++) {
            if(nums[i]%3!=0){
                sum++;
            }
        }
        return sum;
    }
}
Enter fullscreen mode Exit fullscreen mode

Runtime: 0 ms, faster than 100.00% of Java online submissions for Find Minimum Operations to Make All Elements Divisible by Three.

Memory Usage: 41.8 MB, less than 67.92% of Java online submissions for Find Minimum Operations to Make All Elements Divisible by Three.


That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.

Until next post! :)

Top comments (0)