Skip to content
Related Articles

Related Articles

Smallest positive integer K such that all array elements can be made equal by incrementing or decrementing by at most K
  • Last Updated : 01 Mar, 2021

Given an array arr[] of size N, the task is to find the smallest positive integer K such that incrementing or decrementing each array element by K at most once makes all elements equal. If it is not possible to make all array elements equal, then print -1.

Examples :

Input: arr[] = { 5, 7, 9 }
Output: 2
Explanation: 
Incrementing the value of arr[0] by K(= 2) modifies arr[] to { 7, 7, 9 }. 
Decrementing the value of arr[2] by K(= 2) modifies arr[] to { 7, 7, 7 }

Input: arr[] = {1, 3, 9}, N = 3
Output: -1

 

Approach: Follow the steps below to solve the problem :



  • Initialize a Set to store all distinct elements present in the array.
  • Count the distinct elements in the array, which is equal to the size of the Set, say M.
  • If M > 3, then print -1.
  • If M = 3, then check if the difference between the largest and the second largest element of the Set is equal to the difference between the second largest and the third largest element of the Set or not. If found to be true, then print the difference. Otherwise, print -1.
  • If M = 2, then check if the difference between the largest and the second largest element of the set is even or not. If found to be true, then print the half of their difference. Otherwise, print the difference.
  • If M <= 1, then print 0.

Below is the implementation of the above solution :

C++




// C++ program for the above approach
#include <iostream>
#include <set>
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<int> 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<int>::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<Integer> B = new HashSet<Integer>();
       
        // Traverse the array, A[]
        for (int i = 0; i < N; i++)
        {
            B.add(A[i]);
        }
         
        ArrayList<Integer> b = new ArrayList<Integer>(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<int>();
 
    // Traverse the array, A[]
    for (int i = 0; i < N; i++) {
      B.Add(A[i]);
    }
 
    List<int> b = new List<int>(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.


Output: 

2

 

Time Complexity: O(N * log(N))
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :