Minimum operations required to make all Array elements divisible by K - GeeksforGeeks

13 May, 2021
Given an array a[], integer K and an integer X (which is initially initialized to 0). Our task is to find the minimum number of moves required to update the array such that each of its elements is divisible by K by performing the following operations:
Choose one index i from 1 to N and increase ai by X and then increase X by 1. This operation cannot be applied more than once to each element of the array
Only increase the value of X by 1.
Examples:
Input: K = 3, a = [1, 2, 2, 18] Output: 5 Explanation: Initially X = 0 hence update X to 1. For X = 1 add X to the second element of array to make the array [1, 3, 2, 18] and increase X by 1. For X = 2 add X to the first element of array [3, 3, 2, 18] and increase X by 1. For X = 3 just increase X by 1. For X = 4 add X to the third element of array to make the array [3, 3, 6, 18] and increase X by 1. At last, the array becomes [3, 3, 6, 18] where all the elements are divisible by K = 3.Input: K = 5, a[] = [15, 25, 5, 10, 20, 1005, 70, 80, 90, 100] Output: 0 Explanation: Here all elements are already divisible by 5.
Approach: The main idea is to find the maximum value of X that is needed to update the elements of the array to make it divisible by K.
To do this we need to find the maximum value of (K – (ai mod K)) to add to the array elements to make it divisible by K.
However, there can be equal elements so keep track of the number of such elements, using map data structures.
When found another such element in the array then update the answer with (K – (ai mod K)) + (K * number of Equal Elements) because with every move we increase X by 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// Minimum number of moves required to// update the array such that each of// its element is divisible by K #include <bits/stdc++.h>using namespace std; // Function to find the// Minimum number of moves required to// update the array such that each of// its element is divisible by Kvoid compute(int a[], int N, int K){    // Initialize Map data structure    map<long, long> eqVal;     long maxX = 0;     // Iterate for all the elements    // of the array    for (int i = 0; i < N; i++) {         // Calculate the        // value to be added        long val = a[i] % K;         val = (val == 0 ? 0 : K - val);         // Check if the value equals        // to 0 then simply continue        if (val == 0)            continue;         // Check if the value to be        // added is present in the map        if (eqVal.find(val) != eqVal.end()) {             long numVal = eqVal[val];            // Update the answer            maxX = max(maxX,                    val + (K * numVal));             eqVal[val]++;        }         else {            eqVal[val]++;            maxX = max(maxX, val);        }    }     // Print the required result    // We need to add 1 to maxX    // because we cant ignore the    // first move where initially X=0    // and we need to increase it by 1    // to make some changes in array    cout << (maxX == 0 ? 0 : maxX + 1)        << endl;} // Driver codeint main(){    int K = 3;    int a[] = { 1, 2, 2, 18 };    int N = sizeof(a) / sizeof(a[0]);    compute(a, N, K);    return 0;}
// Java implementation to find the// minimum number of moves required to// update the array such that each of// its element is divisible by Kimport java.util.*; class GFG{     // Function to find the minimum// number of moves required to// update the array such that each of// its element is divisible by Kstatic void compute(int a[], int N, int K){         // Initialize Map data structure    Map<Long,        Long> eqVal = new HashMap<Long,                                Long>();     long maxX = 0;     // Iterate for all the elements    // of the array    for(int i = 0; i < N; i++)    {                 // Calculate the        // value to be added        long val = a[i] % K;         val = (val == 0 ? 0 : K - val);         // Check if the value equals        // to 0 then simply continue        if (val == 0)            continue;         // Check if the value to be        // added is present in the map        if (eqVal.containsKey(val))        {            long numVal = eqVal.get(val);                         // Update the answer            maxX = Math.max(maxX,                            val + (K * numVal));             eqVal.put(val,            eqVal.getOrDefault(val, 0l) + 1l);        }        else        {            eqVal.put(val, 1l);            maxX = Math.max(maxX, val);        }    }     // Print the required result    // We need to add 1 to maxX    // because we cant ignore the    // first move where initially X=0    // and we need to increase it by 1    // to make some changes in array    System.out.println(maxX == 0 ? 0 : maxX + 1);} // Driver codepublic static void main(String[] args){    int K = 3;    int a[] = { 1, 2, 2, 18 };    int N = a.length;         compute(a, N, K);}} // This code is contributed by offbeat
# Python3 implementation to find the# Minimum number of moves required to# update the array such that each of# its element is divisible by Kfrom collections import defaultdict # Function to find the Minimum number# of moves required to update the# array such that each of its# element is divisible by Kdef compute(a, N, K):     # Initialize Map data structure    eqVal = defaultdict(int)     maxX = 0     # Iterate for all the elements    # of the array    for i in range(N):         # Calculate the        # value to be added        val = a[i] % K         if (val != 0):            val = K - val         # Check if the value equals        # to 0 then simply continue        if (val == 0):            continue         # Check if the value to be        # added is present in the map        if (val in eqVal):            numVal = eqVal[val]                         # Update the answer            maxX = max(maxX,                    val + (K * numVal))             eqVal[val] += 1        else:            eqVal[val] += 1            maxX = max(maxX, val)     # Print the required result    # We need to add 1 to maxX    # because we cant ignore the    # first move where initially X=0    # and we need to increase it by 1    # to make some changes in array    if maxX == 0:        print(0)    else:        print(maxX + 1)     # Driver codeif __name__ == "__main__":     K = 3    a = [ 1, 2, 2, 18 ]    N = len(a)         compute(a, N, K) # This code is contributed by chitranayal
// C# implementation to find the// minimum number of moves required to// update the array such that each of// its element is divisible by Kusing System;using System.Collections.Generic; class GFG{     // Function to find the minimum// number of moves required to// update the array such that each of// its element is divisible by Kstatic void compute(int []a, int N, int K){         // Initialize Map data structure    Dictionary<long,               long> eqVal = new Dictionary<long,                                            long>();     long maxX = 0;     // Iterate for all the elements    // of the array    for(int i = 0; i < N; i++)    {                 // Calculate the        // value to be added        long val = a[i] % K;         val = (val == 0 ? 0 : K - val);         // Check if the value equals        // to 0 then simply continue        if (val == 0)            continue;         // Check if the value to be        // added is present in the map        if (eqVal.ContainsKey(val))        {            long numVal = eqVal[val];                         // Update the answer            maxX = Math.Max(maxX,                            val + (K * numVal));                                 eqVal[val] = 1 +            eqVal.GetValueOrDefault(val, 0);        }        else        {            eqVal.Add(val, 1);            maxX = Math.Max(maxX, val);        }    }     // Print the required result    // We need to add 1 to maxX    // because we cant ignore the    // first move where initially X=0    // and we need to increase it by 1    // to make some changes in array    Console.Write(maxX == 0 ? 0 : maxX + 1);} // Driver codepublic static void Main(string[] args){    int K = 3;    int []a = { 1, 2, 2, 18 };    int N = a.Length;         compute(a, N, K);}} // This code is contributed by rutvik_56
<script> // Javascript implementation to find the// minimum number of moves required to// update the array such that each of// its element is divisible by K           // Function to find the minimum// number of moves required to// update the array such that each of// its element is divisible by K    function compute(a,N,K)    {        // Initialize Map data structure    let eqVal = new Map();       let maxX = 0;       // Iterate for all the elements    // of the array    for(let i = 0; i < N; i++)    {                   // Calculate the        // value to be added        let val = a[i] % K;           val = (val == 0 ? 0 : K - val);           // Check if the value equals        // to 0 then simply continue        if (val == 0)            continue;           // Check if the value to be        // added is present in the map        if (eqVal.has(val))        {            let numVal = eqVal.get(val);                           // Update the answer            maxX = Math.max(maxX,                            val + (K * numVal));               eqVal.set(val,eqVal.get(val) + 1);        }        else        {            eqVal.set(val, 1);            maxX = Math.max(maxX, val);        }    }       // Print the required result    // We need to add 1 to maxX    // because we cant ignore the    // first move where initially X=0    // and we need to increase it by 1    // to make some changes in array    document.write(maxX == 0 ? 0 : maxX + 1);    }         // Driver code    let K = 3;    let a=[1, 2, 2, 18];    let N = a.length;    compute(a, N, K);          // This code is contributed by avanitrachhadiya2155 </script>
5
Time Complexity: O(N) 
offbeat
ukasp
rutvik_56
avanitrachhadiya2155
divisibility
optimization-technique
Algorithms
Arrays
Competitive Programming
Mathematical
Arrays
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Recursive Practice Problems with Solutions
Playfair Cipher with Examples
Arrays in Java
Stack Data Structure (Introduction and Program)
Arrays in C/C++
Multidimensional Arrays in Java
Program for array rotation