Open In App

Minimize count of Subsets with difference between maximum and minimum element not exceeding K

Last Updated : 19 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[ ] and an integer K, the task is to split the given array into minimum number of subsets having the difference between the maximum and the minimum element ≤ K.

Examples:

Input: arr[ ] = {1, 3, 7, 9, 10}, K = 3
Output: 2
Explanation:
One of the possible subsets of arr[] are {1, 3} and {7, 9, 10} where the difference between maximum and minimum element does not greater than K i.e, 3.

Input: arr[ ] = {1, 10, 8, 3, 9}, K =3
Output: 2.

Approach: Follow the steps below to solve the problem:

  1. Sort the array in ascending order.
  2. Iterate over the array, setting currMin as the first element of the array and keep updating currMax with the elements traversed.
  3. If at any index, the difference between currMax and currMin exceeds K, increment answer by 1 and set currMax and currMin to arr[i].
  4. Finally, return answer.

Below is the implementation of the above approach:

C++




// C++ Program to implement
// above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum count
// of subsets of required type
int findCount(int arr[], int N, int K)
{
    sort(arr, arr + N);
 
    // Stores the result
    int result = 1;
 
    // Store the maximum and minimum
      // element of the current subset
    int cur_max = arr[0];
    int cur_min = arr[0];
   
    for (int i = 1; i < N; i++) {
       
        // Update current maximum
        cur_max = arr[i];
       
        // If difference exceeds K
        if (cur_max - cur_min > K) {
           
            // Update count
            result++;
 
            // Update maximum and minimum
            // to the current subset
            cur_max = arr[i];
            cur_min = arr[i];
        }
    }
   
    return result;
}
 
// Driver Code
int main()
{
    int arr[] = { 1,10, 8, 3, 9 };
    int K = 3;
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << findCount(arr, N, K);
 
    return 0;
}


Java




// Java program to implement
// above approach
import java.util.*;
 
class GFG{
 
// Function to find the minimum count
// of subsets of required type
static int findCount(int arr[], int N, int K)
{
    Arrays.sort(arr);
 
    // Stores the result
    int result = 1;
 
    // Store the maximum and minimum
    // element of the current subset
    int cur_max = arr[0];
    int cur_min = arr[0];
 
    for(int i = 1; i < N; i++)
    {
         
        // Update current maximum
        cur_max = arr[i];
     
        // If difference exceeds K
        if (cur_max - cur_min > K)
        {
         
            // Update count
            result++;
 
            // Update maximum and minimum
            // to the current subset
            cur_max = arr[i];
            cur_min = arr[i];
        }
    }
    return result;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 10, 8, 3, 9 };
    int K = 3;
    int N = arr.length;
     
    System.out.print(findCount(arr, N, K));
}
}
 
// This code is contributed by amal kumar choubey


Python3




# Python3 program to implement
# the above approach
 
# Function to find the minimum count
# of subsets of required type
def findCount(arr, N, K):
 
    arr.sort()
 
    # Stores the result
    result = 1
 
    # Store the maximum and minimum
    # element of the current subset
    cur_max = arr[0]
    cur_min = arr[0]
 
    for i in range(1, N):
 
        # Update current maximum
        cur_max = arr[i]
 
        # If difference exceeds K
        if(cur_max - cur_min > K):
 
            # Update count
            result += 1
 
            # Update maximum and minimum
            # to the current subset
            cur_max = arr[i]
            cur_min = arr[i]
 
    return result
 
# Driver Code
arr = [ 1, 10, 8, 3, 9 ]
K = 3
N = len(arr)
 
# Function call
print(findCount(arr, N, K))
 
# This code is contributed by Shivam Singh


C#




// C# program to implement
// above approach
using System;
class GFG{
 
// Function to find the minimum count
// of subsets of required type
static int findCount(int []arr,
                     int N, int K)
{
    Array.Sort(arr);
 
    // Stores the result
    int result = 1;
 
    // Store the maximum and minimum
    // element of the current subset
    int cur_max = arr[0];
    int cur_min = arr[0];
 
    for(int i = 1; i < N; i++)
    {
         
        // Update current maximum
        cur_max = arr[i];
     
        // If difference exceeds K
        if (cur_max - cur_min > K)
        {
         
            // Update count
            result++;
 
            // Update maximum and minimum
            // to the current subset
            cur_max = arr[i];
            cur_min = arr[i];
        }
    }
    return result;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 1, 10, 8, 3, 9 };
    int K = 3;
    int N = arr.Length;
     
    Console.Write(findCount(arr, N, K));
}
}
 
// This code is contributed by gauravrajput1


Javascript




<script>
// javascript program for the
// above approach
 
// Function to find the minimum count
// of subsets of required type
function findCount(arr, N, K)
{
    arr.sort();
  
    // Stores the result
    let result = 1;
  
    // Store the maximum and minimum
    // element of the current subset
    let cur_max = arr[0];
    let cur_min = arr[0];
  
    for(let i = 1; i < N; i++)
    {
          
        // Update current maximum
        cur_max = arr[i];
      
        // If difference exceeds K
        if (cur_max - cur_min > K)
        {
          
            // Update count
            result++;
  
            // Update maximum and minimum
            // to the current subset
            cur_max = arr[i];
            cur_min = arr[i];
        }
    }
    return result;
}
  
// Driver Code
 
     let arr = [ 1, 10, 8, 3, 9 ];
    let K = 3;
    let N = arr.length;
      
    document.write(findCount(arr, N, K));
  
 // This code is contributed by target_2.
</script>


Output: 

2

 

Time Complexity: O(NLog(N))
Auxiliary Space: O(1)



Similar Reads

Construct a Matrix with no element exceeding X and sum of two adjacent elements not exceeding Y
Given four integers N, M, X and Y, the task is to construct a N * M matrix such that each cell consists of a value in the range [0, X] such that sum of any two adjacent cells should be less than or equal to Y and the total sum of the matrix should be maximum. Example: Input: N = 3, M = 3, X = 5, Y = 3 Output: 3 0 3 0 3 0 3 0 3 Explanation: All the
7 min read
Split array into minimum number of subsets having difference between maximum and minimum element at most K
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: 2Explanation:The given array can be divided into two
6 min read
Count N-length arrays of made up of elements not exceeding 2^K - 1 having maximum sum and Bitwise AND equal to 0
Given two integers N and K, the task is to find the number of N-length arrays that satisfies the following conditions: The sum of the array elements is maximum possible.For every possible value of i ( 1 ? i ? N ), the ith element should lie between 0 and 2K - 1.Also, Bitwise AND of all the array elements should be 0. Note: Since, the answer can be
7 min read
Minimize sum of differences between maximum and minimum elements present in K subsets
Given an array arr[] of size N and an integer K, the task is to minimize the sum of the difference between the maximum and minimum element of each subset by splitting the array into K subsets such that each subset consists of unique array elements only. Examples: Input: arr[] = { 6, 3, 8, 1, 3, 1, 2, 2 }, K = 4 Output: 6 Explanation: One of the opt
12 min read
Queries to calculate maximum Bitwise XOR of X with any array element not exceeding M
Given an array arr[] consisting of N non-negative integers and a 2D array queries[][] consisting of queries of the type {X, M}, the task for each query is to find the maximum Bitwise XOR of X with any array element whose value is at most M. If it is not possible to find the Bitwise XOR, then print "-1". Examples: Input: arr[] = {0, 1, 2, 3, 4}, que
18 min read
Maximize count of pairs (i, j) from two arrays having element from first array not exceeding that from second array
Given two arrays arr1[] and arr2[] of lengths N and M respectively, the task is to find the maximum number of pairs (i, j) such that 2 * arr1[i] ≤ arr2[j] (1 ≤ i ≤ N and 1 ≤ j ≤ M). Note: Any array element can be part of a single pair. Examples: Input: N = 3, arr1[] = {3, 2, 1}, M = 4, arr2[] = {3, 4, 2, 1}Output: 2Explanation:Only two pairs can be
7 min read
Count of N-digit numbers with absolute difference of adjacent digits not exceeding K | Set 2
Given two integers N and K, the task is to find the count of N-digit numbers such that the absolute difference of adjacent digits in the number is not greater than K.Examples: Input: N = 2, K = 1 Output: 26 Explanation: The numbers are 10, 11, 12, 21, 22, 23, 32, 33, 34, 43, 44, 45, 54, 55, 56, 65, 66, 67, 76, 77, 78, 87, 88, 89, 98, 99Input: N = 3
11 min read
Count of N-digit numbers with absolute difference of adjacent digits not exceeding K
Given two integers N and K, the task is to find the count of N-digit numbers such that the absolute difference of adjacent digits in the number is not greater than K. Examples: Input: N = 2, K = 1 Output: 26 Explanation: The numbers are 10, 11, 12, 21, 22, 23, 32, 33, 34, 43, 44, 45, 54, 55, 56, 65, 66, 67, 76, 77, 78, 87, 88, 89, 98, 99 Input: N =
14 min read
Minimize count of flips required such that no substring of 0s have length exceeding K
Given a binary string str of length N and an integer K where K is in the range (1 ? K ? N), the task is to find the minimum number of flips( conversion of 0s to 1 or vice versa) required to be performed on the given string such that the resulting string does not contain K or more zeros together. Examples: Input: str = "11100000011", K = 3 Output: 2
6 min read
Minimize difference between maximum and minimum element by decreasing and increasing Array elements by 1
Given an array arr[], consisting of N positive integers. The task is to minimize the difference between the maximum and the minimum element of the array by performing the below operation any number of times (possibly zero). In one operation choose 2 different index, i and j and decrement arr[i] and increment arr[j] by 1.Notice this operation can be
5 min read
Article Tags :
Practice Tags :