LeetCode 3512: Minimum Operations to Make Array Sum Divisible by K Solution

Master LeetCode problem 3512 (Minimum Operations to Make Array Sum Divisible by K), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3512. Minimum Operations to Make Array Sum Divisible by K

Problem Explanation

Explanation

To solve this problem, we need to find the minimum number of operations required to make the sum of the array divisible by k. We can achieve this by iterating through the array and calculating the sum modulo k. If the sum modulo k is greater than 0, we need to adjust the array elements to reduce the sum modulo k to 0. We can do this by decrementing the elements in the array until the sum becomes divisible by k. The minimum number of operations required will be the sum modulo k.

Algorithm:

  1. Calculate the sum of all elements in the array.
  2. Calculate the sum modulo k.
  3. If the sum modulo k is greater than 0, decrement the elements in the array until the sum becomes divisible by k.
  4. The minimum number of operations required will be the sum modulo k.

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

Solution Code

class Solution {
    public int minOperations(int[] nums, int k) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        int mod = sum % k;
        if (mod == 0) {
            return 0;
        }
        
        int operations = 0;
        int target = sum - (sum / k) * k;
        
        for (int i = 0; i < nums.length; i++) {
            if (mod >= target) {
                return operations;
            }
            if (nums[i] > mod) {
                int diff = Math.min(nums[i] - mod, mod);
                nums[i] -= diff;
                mod -= diff;
                operations += diff;
            }
        }
        
        return operations;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3512 (Minimum Operations to Make Array Sum Divisible by K)?

This page provides optimized solutions for LeetCode problem 3512 (Minimum Operations to Make Array Sum Divisible by K) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3512 (Minimum Operations to Make Array Sum Divisible by K)?

The time complexity for LeetCode 3512 (Minimum Operations to Make Array Sum Divisible by K) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3512 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3512 in Java, C++, or Python.

Back to LeetCode Solutions