×

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

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas...

3 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Scanner in Java

Static way of Programming: When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a...

4 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Java 9 Tutorial

The Java 9 is most popular release of java programming to make it platform modular. It is used to improve JDK and java implementation security. It provides JAVA SE and...

3 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

CopyOnWriteArrayList in Java

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating...

5 minutes read.

Camel Case in Java

Java names its classes, interfaces, methods, as well as variables using camel-case syntax. If the name consists of two words, the second word will always begin with a capital letter,...

3 minutes read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.