text: Maximize count of elements that can be selected having minimum difference between their sum and K | C ++ implementation of the above approach ; Function to count maximum number of elements that can be selected ; Sort the array ; Traverse the array ; Add current element to the sum ; IF sum exceeds k ; Increment count ; Return the count ; Driver Code ; Function call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountMaximum ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int sum = 0 , count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum > k ) break ; count ++ ; } return count ; } int main ( ) { int arr [ ] = { 30 , 30 , 10 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 50 ; cout << CountMaximum ( arr , n , k ) ; return 0 ; }