DDSA Solutions

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

Time: O(n)
Space: O(1)
Advertisement

Approach

For each element cost = min(n % 3, 3 - n % 3); sum all costs.

Key Techniques

Array

Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.

Math

Math problems test number theory, combinatorics, and modular arithmetic. Common tools: GCD/LCM (Euclidean algorithm), prime sieve, modular inverse (Fermat's little theorem), digit manipulation, and bit tricks. Overflow is a key concern in C# — use long when products may exceed 2³¹.

3190.cs
C#
// Approach: For each element cost = min(n % 3, 3 - n % 3); sum all costs.
// Time: O(n) Space: O(1)

public class Solution
{
    public int MinimumOperations(int[] nums)
    {
        int totalOperations = 0;

        // Iterate through each number in the array
        foreach (int number in nums)
        {
            // Calculate the remainder when divided by 3
            int remainder = number % 3;

            // If the number is not divisible by 3, we need operations
            if (remainder != 0)
                // We can either subtract the remainder to reach a multiple of 3
                // or add (3 - remainder) to reach the next multiple of 3
                // Choose the minimum of these two options
                totalOperations += Math.Min(remainder, 3 - remainder);
        }

        return totalOperations;
    }
}
Advertisement
Was this solution helpful?