×

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference between the groups with the highest and lowest sums is as small as possible. Keep in mind that each element can only belong to one group. Additionally, leaving any piece is prohibited. To put it another way, an element must belong to a group.

Example

int a [ ] = {4, 7 , 0 , 2 , 3 , 6}

Explanation

G1 = {4, 6}, G2 = {0, 2}, G3 = {7, 6}, G4 = {7, 3}

G1 = 4 + 6 = 10 , G2 = 0 + 2 = 2 , G3 = 7 + 6 = 13 , G4 = 7 + 3 = 10

As a result, we can observe that the minimum sum is 2 and maximum sums  is 13. The difference is therefore 13-2 = 11.

Approach

The process is easy. To ensure that the distance between the maximum and minimum is as little as possible, one must maintain the maximum at the lowest value and the minimum at the greatest value. To achieve this, we must combine the array's integers in a way that the largest element is mapped to the smallest element, and the second largest element is mapped to the largest element. The array must be sorted before the final member is combined (made into a group) with the first element, the second-last element with the second element, and so forth. 

Java Program to find minimum difference between groups of size of two

MinDiff.java

// important import statement  
import java.util.Arrays;  
import java.util.ArrayList;  
 
public class Mindiff
{  


private int Min ( int a , int b )  
{  
if ( a > b )  
{  
    return b;  
}  
  
return a;  
}  


private int Max ( int x , int y )  
{  
if ( x > y )  
{  
    return x ;  
}  
  
return y ;  
}  
  


public int MinDiff ( int arr[] , int s1 )  
{  
    if ( s1 % 2 != 0 )  
    {  
        return -1 ;  
    }  
    Arrays . sort ( arr ) ;  
    int dif = Integer . MAX_VALUE ;  
    ArrayList < Integer > a = new ArrayList < Integer > ( ) ;  
    for ( int j = 0 , k = s1 - 1 ; j < k ; k-- , j++ )  
    {  
        
        a . add ( arr [ j ] + arr [ k ] ) ;  
    }  
    int min = Integer . MAX_VALUE ;  
 
    int max = Integer . MIN_VALUE ;  
 
    int size = a . size ( ) ;  
      
    for ( int j = 0 ;  j < size ;  j++ )  
    {  
        min = Min ( min , a . get ( j ) ) ;  
        max = Max(max, a.get(j));  
    }  
      
    return (max - min);  
}  
 
public static void main(String[] args)   
{  
Main obj = new Main();  


int a [] = { 1 , 2 , 4 , 6 , 10 , 11 , 23 , 7 } ;  
int size_Of_array = a . length ;  
System.out.println("Input array: ");  
for(int i = 0; i < size_Of_array; i++)  
{  
    System.out.print(a[i] + " ");  
}  
System.out.println();  
  
int ans = obj.MinDiff(a, size_Of_array);  
  
if(ans != -1)  
{  
System.out.println(" Minimum difference : " + ans);  
}  
else  
{  
System.out.println("It is not possible to find the minimum difference.");  
}  
  
System.out.println("\n");  


int a1[] = {4, 11, 5, 3, 7, 2};  
size_Of_array = a1.length;  
  
System.out.println("For the input array: ");  
for(int i = 0; i < size_Of_array; i++)  
{  
    System.out.print(a1[i] + " ");  
}  
System . out . println();  
  
ans = obj . MinDiff ( a1 , size_Of_array ) ;  
if ( ans != -1 )  
{  
System . out . println (" Minimum difference : " + ans ) ;  
}  
else  
{  
System . out . println ("  Not possible to find the minimum difference. " ) ;  
}  
System . out . println ( " \n ") ;  
int a2 [ ]  = { 3 , 2 , 1 , 0 , 34 , 20 , 35 } ;  
size_Of_array = a2 . length ;  
System . out . println ( " For the input array: " ) ;  
for ( int i = 0 ; i < size_Of_array ; i++ )  
{  
    System . out . print ( a2 [ i ]  + " " ) ;  
}  
System . out . println ( ) ;  
ans = obj . MinDiff ( a2 , size_Of_array ) ;  
if ( ans != -1 )  
{  
System . out . println( " The minimum difference is: " + ans ) ;  
}  
else  
{  
System . out . println ( " It is not possible to find the minimum difference. " ) ;  
}  
System . out . println ( " \n " ) ;  
  
}  
}  

Output

Minimum Difference Between Groups of Size Two in Java

Another Approach to find minimum difference between groups of size two in Java.

MinDiff2.java

import java.io.*;
import java.util.*;
class MinDiff2 {


static int cal ( int[] arr , int n )
{
Arrays . sort ( arr ) ;


int min = arr [ 0 ] + arr [ n - 1 ] ;
int max =  arr [ 0 ] +  arr [ n - 1 ]  ;


for ( int j = 1, k = n - 1; j < k; j++, k --) {
if ( arr [ j ] + arr [ k ] > max )
{
max = arr [ j ] + arr [ k ] ;
}
if (arr [ j ] + arr [ k ] < min )
{
min = arr [ j ] + arr [ k ];
}
}


return Math . abs ( max - min ) ;
}


public static void main ( String [ ]  args )
{
int [ ] a = { 12 , 16 , 24 , 23 } ;
int len = a . length ;
System . out . print ( cal ( a , len ) ) ;
}
}

Output

Minimum Difference Between Groups of Size Two in Java

Related Topics

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Hogben Numbers in Java

In this section, we will discover what the Hogben number is and develop Java programs that compute it. Java coding interviews and academic exams typically involve questions about the Hogben...

3 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

Advanced Java skills

These were some of the contemporary talents that a Java developer should master in efforts to progress in the era of science in 2022. A database such as MySQL, a...

4 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Types of Statements in Java

In natural languages, statements and sentences are roughly equivalent. In general, statements are similar to valid English sentences. We will talk about a statement in Java and the different kinds...

11 minutes read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.