Maximize count of elements that can be selected having minimum difference between their sum and K | Java implementation of the above approach ; Function to count maximum number of elements that can be selected ; Sorting the array ; Traverse the array ; Add the current element to the sum ; If sum exceeds k ; Increment count ; Returning the count ; Driver code ; Function call
import java . util . Arrays ; public class GFG { static int CountMaximum ( int arr [ ] , int n , int k ) { Arrays . sort ( arr ) ; int sum = 0 , count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum > k ) break ; count ++ ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 30 , 30 , 10 , 10 } ; int n = 4 ; int k = 50 ; System . out . println ( CountMaximum ( arr , n , k ) ) ; } }