Maximize number of elements from Array with sum at most K | Java program for the above approach ; Function to select a maximum number of elements in array whose sum is at most K ; Sort the array ; Calculate the sum and count while iterating the sorted array ; Iterate for all the elements in the array ; Add the current element to sum ; Increment the count ; Return the answer ; Driver Code ; Given array ; Given sum k ; Function call
import java . util . * ; class GFG { static int maxSelections ( int A [ ] , int n , int k ) { Arrays . sort ( A ) ; int sum = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + A [ i ] ; if ( sum > k ) { break ; } count ++ ; } return count ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 7 , 2 , 9 , 4 } ; int k = 15 ; int n = A . length ; System . out . print ( maxSelections ( A , n , k ) ) ; } }