Maximize number of elements from Array with sum at most K | 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 ; Given array ; Given sum k ; Function Call
function maxSelections ( A , n , k ) { A . sort ( ) ; let sum = 0 ; let count = 0 ; for ( let i = 0 ; i < n ; i ++ ) { sum = sum + A [ i ] ; if ( sum > k ) { break ; } count ++ ; } return count ; } let A = [ 3 , 7 , 2 , 9 , 4 ] ; let k = 15 ; let n = A . length ; document . write ( maxSelections ( A , n , k ) ) ;