DEV Community

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

Posted on

1 1

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! :)

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay