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

📅  最后修改于: 2021-09-03 03:20:46             🧑  作者: Mango

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

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

例子:

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

  • 为此,我们需要找到(K – (a i mod K))最大值以添加到数组元素中,使其可被 K 整除。
  • 但是,可以有相等的元素,因此请使用地图数据结构跟踪此类元素的数量。
  • 当在数组中找到另一个这样的元素时,用(K – (a i mod K)) + (K * 相等元素的数量)更新答案,因为每移动一次,我们就将 X 增加 1。

下面是上述方法的实现:

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 Classes Live