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 ; Driver Code ; Given array ; Given sum k ; Function call
def maxSelections ( A , n , k ) : NEW_LINE INDENT A . sort ( ) ; NEW_LINE sum = 0 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + A [ i ] ; NEW_LINE if ( sum > k ) : NEW_LINE break ; NEW_LINE count += 1 ; NEW_LINE return count ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 7 , 2 , 9 , 4 ] ; NEW_LINE k = 15 ; NEW_LINE n = len ( A ) ; NEW_LINE print ( maxSelections ( A , n , k ) ) ; NEW_LINE DEDENT