Split Array into min number of subsets with difference between each pair greater than 1
Last Updated :
25 Jan, 2022
Given an array arr[] of size N, the task is to split the array into a minimum number of subset such that each pair of elements in each subset have the difference strictly greater than 1.
Note: All elements in the array are distinct.
Examples:
Input: arr = {5, 10, 6, 50}
Output: 2
Explanation:
Possible partitions are: {5, 10, 50}, {6}
Input: arr = {2, 4, 6}
Output: 1
Explanation:
Possible partitions are: {2, 4, 6}
Approach: The idea is to observe that if there is no such pair i, j such that |arr[i] – arr[j]| = 1, then it is possible to put all the elements in the same partition, otherwise divide them into two partitions. So the required minimum number of partitions is always 1 or 2.
- Sort the given array.
- Compare the adjacent elements. If at any point their difference to be equal to 1, then print “2” as the required number of subset partition will always be 2 as we can put one of the elements from the above pair into another subset.
- If we traversed all the array didn’t found any adjacent pair with a difference less than 2 then print “1” without splitting the array into subsets we can have all possible pairs difference at least 2.
Below is the implementation for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void split( int arr[], int n)
{
sort(arr, arr + n);
int count = 1;
for ( int i = 1; i < n; i++) {
if (arr[i] - arr[i - 1] == 1) {
count = 2;
break ;
}
}
cout << count << endl;
}
int main()
{
int arr[] = { 2, 4, 6 };
int n = sizeof (arr) / sizeof ( int );
split(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void split( int arr[], int n)
{
Arrays.sort(arr);
int count = 1 ;
for ( int i = 1 ; i < n; i++)
{
if (arr[i] - arr[i - 1 ] == 1 )
{
count = 2 ;
break ;
}
}
System.out.print(count);
}
public static void main(String[] args)
{
int arr[] = { 2 , 4 , 6 };
int n = arr.length;
split(arr, n);
}
}
|
Python3
def split(arr, n):
arr.sort()
count = 1
for i in range ( 1 , n):
if (arr[i] - arr[i - 1 ] = = 1 ):
count = 2
break
print (count)
if __name__ = = '__main__' :
arr = [ 2 , 4 , 6 ]
n = len (arr)
split(arr, n)
|
C#
using System;
class GFG{
static void split( int []arr, int n)
{
Array.Sort(arr);
int count = 1;
for ( int i = 1; i < n; i++)
{
if (arr[i] - arr[i - 1] == 1)
{
count = 2;
break ;
}
}
Console.Write(count);
}
public static void Main( string [] args)
{
int [] arr = new int []{ 2, 4, 6 };
int n = arr.Length;
split(arr, n);
}
}
|
Javascript
<script>
function split(arr, n)
{
arr.sort();
let count = 1;
for (let i = 1; i < n; i++)
{
if (arr[i] - arr[i - 1] == 1)
{
count = 2;
break ;
}
}
document.write(count);
}
let arr = [ 2, 4, 6 ];
let n = arr.length;
split(arr, n);
</script>
|
Time Complexity: O(N log N), where N is the length of the array.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...