Open In App

Split array into minimum number of subsets having difference between maximum and minimum element at most K

Last Updated : 22 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum number of sets, the array elements can be divided into such that the difference between the maximum and minimum element of each set is at most K.

Examples:

Input: arr[] = {1, 2, 3, 4, 5}, K = 2 
Output: 2
Explanation:
The given array can be divided into two sets {1, 2, 3} having the difference between maximum and minimum as 3 – 1= 2 and {4, 5} having the difference between maximum and minimum as 5 – 4 = 1.

Input: arr[] = {5, 2, 9, 7, 3, 2, 4, 6, 14, 10}, K = 3
Output: 4

 

Approach: The given problem can be solved by sorting the given array and finding the minimum number of subarrays the array elements can be broken such that the difference between the maximum and minimum element at most K. Follow the steps below to solve the given problem:

  • Sort the given array arr[] in non-decreasing order.
  • Initialize two iterators begin and end as 0 representing the beginning and end of each set.
  • Initialize a variable, say setCount as 1 that stores the resultant minimum number of breaking of array elements into subarrays.
  • Iterate a loop until the value of end is less than N and perform the following steps:
    1. If the value of arr[end] – arr[begin] <= K, then increment the value of end.
    2. Otherwise, increment the value setCount by 1 and update the value of begin to end representing the new set.
  • After completing the above steps, print the value of setCount as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum number
// of sets the array can be divided such
// that for each set max-min <= K
int minSetCount(int arr[], int N, int K)
{
    // Sort the input array
    sort(arr, arr + N);
 
    // Stores the count of set required
    int setCount = 1;
 
    // Stores the beginning and ending
    // of the current set
    int begin = 0, end = 0;
 
    // Loop to iterate over the array
    while (end < N) {
 
        // If arr[end] can be included
        // in the current set else
        // begin a new set
        if (arr[end] - arr[begin] <= K) {
            end++;
        }
        else {
            // Increment the set count
            setCount++;
            begin = end;
        }
    }
 
    // Return answer
    return setCount;
}
 
// Driver Code
int main()
{
    int arr[] = { 5, 2, 9, 7, 3, 2, 4, 6, 14, 10 };
    int N = sizeof(arr) / sizeof(int);
    int K = 3;
    cout << minSetCount(arr, N, K);
 
    return 0;
}


Java




// Java program for the above approach
 
import java.util.*;
 
class GFG {
 
    // Function to find the minimum number
    // of sets the array can be divided such
    // that for each set max-min <= K
    static int minSetCount(int[] arr, int N, int K)
    {
        // Sort the input array
        Arrays.sort(arr);
 
        // Stores the count of set required
        int setCount = 1;
 
        // Stores the beginning and ending
        // of the current set
        int begin = 0, end = 0;
 
        // Loop to iterate over the array
        while (end < N) {
 
            // If arr[end] can be included
            // in the current set else
            // begin a new set
            if (arr[end] - arr[begin] <= K) {
                end++;
            }
            else {
                // Increment the set count
                setCount++;
                begin = end;
            }
        }
 
        // Return answer
        return setCount;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 5, 2, 9, 7, 3, 2, 4, 6, 14, 10 };
        int N = arr.length;
        int K = 3;
        System.out.print(minSetCount(arr, N, K));
    }
}
 
// This code is contributed by subham348.


Python3




# Python 3 program for the above approach
 
# Function to find the minimum number
# of sets the array can be divided such
# that for each set max-min <= K
def minSetCount(arr, N, K):
    # Sort the input array
    arr.sort()
 
    # Stores the count of set required
    setCount = 1
 
    # Stores the beginning and ending
    # of the current set
    begin = 0
    end = 0
 
    # Loop to iterate over the array
    while (end < N):
       
        # If arr[end] can be included
        # in the current set else
        # begin a new set
        if (arr[end] - arr[begin] <= K):
            end += 1
        else:
            # Increment the set count
            setCount += 1
            begin = end
 
    # Return answer
    return setCount
 
# Driver Code
if __name__ == '__main__':
    arr = [5, 2, 9, 7, 3, 2, 4, 6, 14, 10]
    N = len(arr)
    K = 3
    print(minSetCount(arr, N, K))
 
    # This code is contributed by SURENDRA_GANGWAR.


C#




// C# program for the above approach
using System;
 
public class GFG
{
 
    // Function to find the minimum number
    // of sets the array can be divided such
    // that for each set max-min <= K
    static int minSetCount(int[] arr, int N, int K)
    {
       
        // Sort the input array
        Array.Sort(arr);
 
        // Stores the count of set required
        int setCount = 1;
 
        // Stores the beginning and ending
        // of the current set
        int begin = 0, end = 0;
 
        // Loop to iterate over the array
        while (end < N) {
 
            // If arr[end] can be included
            // in the current set else
            // begin a new set
            if (arr[end] - arr[begin] <= K) {
                end++;
            }
            else {
                // Increment the set count
                setCount++;
                begin = end;
            }
        }
 
        // Return answer
        return setCount;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int[] arr = { 5, 2, 9, 7, 3, 2, 4, 6, 14, 10 };
        int N = arr.Length;
        int K = 3;
        Console.WriteLine(minSetCount(arr, N, K));
    }
}
 
// This code is contributed by AnkThon


Javascript




<script>
        // JavaScript Program to implement
        // the above approach
 
 
        // Function to find the minimum number
        // of sets the array can be divided such
        // that for each set max-min <= K
        function minSetCount(arr, N, K) {
            // Sort the input array
            arr.sort(function (a, b) { return a - b })
 
            // Stores the count of set required
            let setCount = 1;
 
            // Stores the beginning and ending
            // of the current set
            let begin = 0, end = 0;
 
            // Loop to iterate over the array
            while (end < N) {
 
                // If arr[end] can be included
                // in the current set else
                // begin a new set
                if (arr[end] - arr[begin] <= K) {
                    end++;
                }
                else {
                    // Increment the set count
                    setCount++;
                    begin = end;
                }
            }
 
            // Return answer
            return setCount;
        }
 
        // Driver Code
        let arr = [5, 2, 9, 7, 3, 2, 4, 6, 14, 10];
        let N = arr.length;
        let K = 3;
        document.write(minSetCount(arr, N, K));
 
// This code is contributed by Potta Lokesh
 
    </script>


Output: 

4

 

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



Similar Reads

Split array into minimum number of subsets having maximum pair sum at most K
Given an array, arr[] of size N and an integer K, the task is to partition the array into the minimum number of subsets such that the maximum pair sum in each subset is less than or equal to K. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 5Output: 3Explanation:Subset having maximum pair sum less than or equal to K(= 5) are: {{2, 3}, {1, 4}, {5}}.T
7 min read
Split array into maximum possible subsets having product of their length with the maximum element at least K
Given an array arr[] consisting of N integers and a positive integer K, the task is to maximize the number of subsets having a product of its size and its maximum element at least K by dividing array element into disjoint subsets. Examples: Input: N = 5, K = 4, arr[] = {1, 5, 4, 2, 3}Output: 3Explanation:The array can be split into 3 possible subse
6 min read
Maximum number of subsets an array can be split into such that product of their minimums with size of subsets is at least K
Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum number of disjoint subsets that the given array can be split into such that the product of the minimum element of each subset with the size of the subset is at least K. Examples: Input: arr[] = {7, 11, 2, 9, 5}, K = 10Output: 2Explanation:All such disjoi
8 min read
Split array into minimum number of subsets such that elements of all pairs are present in different subsets at least once
Given an array arr[] consisting of N distinct integers, the task is to find the minimum number of times the array needs to be split into two subsets such that elements of each pair are present into two different subsets at least once. Examples: Input: arr[] = { 3, 4, 2, 1, 5 } Output: 3 Explanation: Possible pairs are { (1, 2), (1, 3), (1, 4), (1,
6 min read
Count ways to split array into two subsets having difference between their sum equal to K
Given an array A[] of size N and an integer diff, the task is to count the number of ways to split the array into two subsets (non-empty subset is possible) such that the difference between their sums is equal to diff. Examples: Input: A[] = {1, 1, 2, 3}, diff = 1 Output: 3 Explanation: All possible combinations are as follows: {1, 1, 2} and {3}{1,
14 min read
Split array into minimum number of subsets with every element of a subset divisible by its minimum
Given an array arr[] of size N, the task is to split the array into the minimum number of subsets such that every element belongs to exactly one subset and is divisible by the minimum element present in each subset. Examples: Input: arr[] = {10, 2, 3, 5, 4, 2}Output: 3Explanation:The three possible groups are: {5, 10}, where all the element is divi
7 min read
Split an Array A[] into Subsets having equal Sum and sizes equal to elements of Array B[]
Given an array A[] consisting of N integers, the task is to split the array A[] into subsets having equal sum and of length equal to elements in array B[]. Examples: Input: A[] = {17, 13, 21, 20, 50, 29}, B[] = {2, 3, 1} Output: 21 29 17 13 20 50 Input: A[] = { 1, 2, 3, 4, 5, 6}, B[] = { 2, 2, 2} Output: 1 6 2 5 3 4 Approach: Follow the steps below
8 min read
Split array into equal length subsets with maximum sum of Kth largest element of each subset
Given an array arr[] of size N, two positive integers M and K, the task is to partition the array into M equal length subsets such that the sum of the Kth largest element of all these subsets is maximum. If it is not possible to partition the array into M equal length subsets, then print -1. Examples: Input: arr[] = { 1, 2, 3, 4, 5, 6 }, M = 2, K =
7 min read
Split Array into min number of subsets with difference between each pair greater than 1
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: 2Explanation: Possible partitions are: {5, 10, 50}, {6} Input: arr = {2,
5 min read
Minimum length of a rod that can be split into N equal parts that can further be split into given number of equal parts
Given an array arr[] consisting of N positive integers, the task is to find the minimum possible length of a rod that can be cut into N equal parts such that every ith part can be cut into arr[i] equal parts. Examples: Input: arr[] = {1, 2}Output: 4Explanation:Consider the length of the rod as 4. Then it can be divided in 2 equal parts, each having
7 min read