Minimize count of Subsets with difference between maximum and minimum element not exceeding K | C ++ Program to implement above approach ; Function to find the minimum count of subsets of required type ; Stores the result ; Store the maximum and minimum element of the current subset ; Update current maximum ; If difference exceeds K ; Update count ; Update maximum and minimum to the current subset ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCount ( int arr [ ] , int N , int K ) { sort ( arr , arr + N ) ; int result = 1 ; int cur_max = arr [ 0 ] ; int cur_min = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { cur_max = arr [ i ] ; if ( cur_max - cur_min > K ) { result ++ ; cur_max = arr [ i ] ; cur_min = arr [ i ] ; } } return result ; } 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 ; }