📌  相关文章
📜  使所有Array元素可被K整除所需的最少操作

📅  最后修改于: 2021-06-26 19:47:09             🧑  作者: Mango

给定一个数组a []整数K和一个整数X (初始初始化为0)。我们的任务是通过执行以下操作来找到更新数组所需的最小移动数,以使数组的每个元素都能被K整除:

  • 从1到N中选择一个索引i ,然后i增加X ,然后将X增加1。此操作不能对数组的每个元素多次应用
  • 仅将X的值增加1。

例子:

方法:主要思想是找到更新数组元素以使其可被K整除所需的X的最大值。

  • 为此,我们需要找到(K –( i mod K))最大值,以添加到数组元素中,以使其可以被K整除。
  • 但是,可以有相等的元素,因此请使用地图数据结构跟踪此类元素的数量。
  • 因为与每一个动作我们增加1 X +(K *相等的元素的数目) –当在阵列中发现的另一种这样的元件然后更新与((一个I MOD K)K)的答案。

下面是上述方法的实现:

C++
// 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 
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 K
void compute(int a[], int N, int K)
{
    // Initialize Map data structure
    map 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 code
int main()
{
    int K = 3;
    int a[] = { 1, 2, 2, 18 };
    int N = sizeof(a) / sizeof(a[0]);
    compute(a, N, K);
    return 0;
}


Java
// Java implementation to find the
// minimum number of moves required to
// update the array such that each of
// its element is divisible by K
import 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 K
static void compute(int a[], int N, int K)
{
     
    // Initialize Map data structure
    Map eqVal = new HashMap();
 
    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 code
public 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
# Python3 implementation to find the
# Minimum number of moves required to
# update the array such that each of
# its element is divisible by K
from 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 K
def 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 code
if __name__ == "__main__":
 
    K = 3
    a = [ 1, 2, 2, 18 ]
    N = len(a)
     
    compute(a, N, K)
 
# This code is contributed by chitranayal


C#
// C# implementation to find the
// minimum number of moves required to
// update the array such that each of
// its element is divisible by K
using 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 K
static void compute(int []a, int N, int K)
{
     
    // Initialize Map data structure
    Dictionary eqVal = new Dictionary();
 
    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 code
public 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


Javascript


输出:
5

时间复杂度: O(N)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。