📌  相关文章
📜  最小正整数K,这样所有数组元素都可以通过最多递增或递减K来相等

📅  最后修改于: 2021-05-14 02:05:06             🧑  作者: Mango

给定大小为N的数组arr [] ,任务是找到最小的正整数K ,以使每个数组元素最多递增或递减K一次,使所有元素相等。如果不可能使所有数组元素相等,则打印-1

例子 :

方法:请按照以下步骤解决问题:

  • 初始化一个Set以存储数组中存在的所有不同元素。
  • 计算数组中的不同元素,该元素等于Set的大小,例如M。
  • 如果M> 3 ,则打印-1
  • 如果M = 3 ,则检查集合最大和第二大元素之间的差是否等于集合最大第二和第三大元素之间的差。如果发现是正确的,则打印差异。否则,打印-1
  • 如果M = 2 ,则检查集合中最大元素和第二大元素之间的差异是否相等。如果发现是正确的,则打印其差额的一半。否则,打印差异。
  • 如果M <= 1 ,则打印0

下面是上述解决方案的实现:

C++
// C++ program for the above approach
#include 
#include 
using namespace std;
 
// Function to find smallest integer K such that
// incrementing or decrementing each element by
// K at most once makes all elements equal
void findMinKToMakeAllEqual(int N, int A[])
{
 
    // Store distinct
    // array elements
    set B;
 
    // Traverse the array, A[]
    for (int i = 0; i < N; i++)
        B.insert(A[i]);
 
    // Count elements into the set
    int M = B.size();
 
    // Iterator to store first
    // element of B
    set::iterator itr = B.begin();
 
    // If M is greater than 3
    if (M > 3)
        printf("-1");
 
    // If M is equal to 3
    else if (M == 3) {
 
        // Stores the first
        // smallest element
        int B_1 = *itr;
 
        // Stores the second
        // smallest element
        int B_2 = *(++itr);
 
        // Stores the largest element
        int B_3 = *(++itr);
 
        // IF difference between B_2 and B_1
        // is equal to B_3 and B_2
        if (B_2 - B_1 == B_3 - B_2)
            printf("%d", B_2 - B_1);
        else
            printf("-1");
    }
 
    // If M is equal to 2
    else if (M == 2) {
 
        // Stores the smallest element
        int B_1 = *itr;
 
        // Stores the largest element
        int B_2 = *(++itr);
 
        // If difference is an even
        if ((B_2 - B_1) % 2 == 0)
            printf("%d", (B_2 - B_1) / 2);
        else
            printf("%d", B_2 - B_1);
    }
 
    // If M is equal to 1
    else
        printf("%d", 0);
}
 
// Driver Code
int main()
{
 
    // Given array
    int A[] = { 1, 3, 5, 1 };
 
    // Given size
    int N = sizeof(A) / sizeof(A[0]);
 
    // Print the required smallest integer
    findMinKToMakeAllEqual(N, A);
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
     
    // Function to find smallest integer K such that
    // incrementing or decrementing each element by
    // K at most once makes all elements equal
    static void findMinKToMakeAllEqual(int N, int A[])
    {
       
        // Store distinct
        // array elements
        Set B = new HashSet();
       
        // Traverse the array, A[]
        for (int i = 0; i < N; i++)
        {
            B.add(A[i]);
        }
         
        ArrayList b = new ArrayList(B);
       
        // Count elements into the set
        int M = b.size();
        int i = 0;
       
        // If M is greater than 3
        if (M > 3)
        {    System.out.print("-1");}
         
         
        // If M is equal to 3
        else if (M == 3)
        {
           
            // Stores the first
            // smallest element
            int B_1 = b.get(i++);
             
            // Stores the second
            // smallest element
            int B_2 =  b.get(i++);
             
            // Stores the largest element
            int B_3 = b.get(i++);
             
            // IF difference between B_2 and B_1
            // is equal to B_3 and B_2
            if (B_2 - B_1 == B_3 - B_2)
            {
                System.out.print(B_2 - B_1);
            }
            else
            {
                System.out.print("-1");
            }
             
             
        }
         
        // If M is equal to 2
        else if (M == 2)
        {
           
            // Stores the smallest element
            int B_1 = b.get(i++);
             
            // Stores the largest element
            int B_2 = b.get(i++);
             
            // If difference is an even
            if ((B_2 - B_1) % 2 == 0)
            {
                System.out.print((B_2 - B_1) / 2);
            }
             
            else
            {
                System.out.print(B_2 - B_1);
            }
        }
        // If M is equal to 1
        else
        {
            System.out.print(0);
        }
    }
     
  // Driver code
    public static void main (String[] args)
    {
         
        // Given array
        int A[] = { 1, 3, 5, 1 };
  
        // Given size
        int N = A.length;
         
         
        // Print the required smallest integer
        findMinKToMakeAllEqual(N, A);
    }
}
 
// This code is contributed by rag2127


Python3
# Python3 program for the above approach
 
# Function to find smallest integer K such
# that incrementing or decrementing each
# element by K at most once makes all
# elements equal
def findMinKToMakeAllEqual(N, A):
     
    # Store distinct
    # array elements
    B = {}
     
    # Traverse the array, A[]
    for i in range(N):
        B[A[i]] = 1
         
    # Count elements into the set
    M = len(B)
     
    # Iterator to store first
    # element of B
    itr, i = list(B.keys()), 0
     
    # If M is greater than 3
    if (M > 3):
        print("-1")
 
    # If M is equal to 3
    elif (M == 3):
         
        # Stores the first
        # smallest element
        B_1, i = itr[i], i + 1
         
        # Stores the second
        # smallest element
        B_2, i = itr[i], i + 1
 
        # Stores the largest element
        B_3, i = itr[i], i + 1
 
        # IF difference between B_2 and B_1
        # is equal to B_3 and B_2
        if (B_2 - B_1 == B_3 - B_2):
            print(B_2 - B_1)
        else:
            print("-1")
 
    # If M is equal to 2
    elif (M == 2):
         
        # Stores the smallest element
        B_1, i = itr[i], i + 1
         
        # Stores the largest element
        B_2, i = itr[i], i + 1
         
        # If difference is an even
        if ((B_2 - B_1) % 2 == 0):
            print((B_2 - B_1) // 2)
        else:
            print(B_2 - B_1)
 
    # If M is equal to 1
    else:
        print(0)
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    A = [ 1, 3, 5, 1 ]
     
    # Given size
    N = len(A)
 
    # Print the required smallest integer
    findMinKToMakeAllEqual(N, A)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
 
  // Function to find smallest integer K such that
  // incrementing or decrementing each element by
  // K at most once makes all elements equal
  static void findMinKToMakeAllEqual(int N, int[] A)
  {
 
    // Store distinct
    // array elements
    var B = new HashSet();
 
    // Traverse the array, A[]
    for (int i = 0; i < N; i++) {
      B.Add(A[i]);
    }
 
    List b = new List(B);
 
    // Count elements into the set
    int M = b.Count;
    int j = 0;
 
    // If M is greater than 3
    if (M > 3) {
      Console.Write("-1");
    }
 
    // If M is equal to 3
    else if (M == 3) {
 
      // Stores the first
      // smallest element
      int B_1 = b[j++];
 
      // Stores the second
      // smallest element
      int B_2 = b[j++];
 
      // Stores the largest element
      int B_3 = b[j++];
 
      // IF difference between B_2 and B_1
      // is equal to B_3 and B_2
      if (B_2 - B_1 == B_3 - B_2) {
        Console.Write(B_2 - B_1);
      }
      else {
        Console.Write("-1");
      }
    }
 
    // If M is equal to 2
    else if (M == 2) {
 
      // Stores the smallest element
      int B_1 = b[j++];
 
      // Stores the largest element
      int B_2 = b[j++];
 
      // If difference is an even
      if ((B_2 - B_1) % 2 == 0) {
        Console.Write((B_2 - B_1) / 2);
      }
 
      else {
        Console.Write(B_2 - B_1);
      }
    }
    // If M is equal to 1
    else {
      Console.Write(0);
    }
  }
 
  // Driver code
  public static void Main(string[] args)
  {
 
    // Given array
    int[] A = { 1, 3, 5, 1 };
 
    // Given size
    int N = A.Length;
 
    // Print the required smallest integer
    findMinKToMakeAllEqual(N, A);
  }
}
 
// This code is contributed by chitranayal.


输出:
2

时间复杂度: O(N * log(N))
辅助空间: O(N)