Maximise the number of toys that can be purchased with amount K | This functions returns the required number of toys ; sort the cost array ; Check if we can buy ith toy or not ; Increment count ; Driver Code
function maximum_toys ( cost , N , K ) { let count = 0 , sum = 0 ; cost . sort ( function ( a , b ) { return a - b } ) ; for ( let i = 0 ; i < N ; i ++ ) { if ( sum + cost [ i ] <= K ) { sum = sum + cost [ i ] ; count ++ ; } } return count ; } let K = 50 ; let cost = [ 1 , 12 , 5 , 111 , 200 , 1000 , 10 , 9 , 12 , 15 ] ; let N = cost . length ; document . write ( maximum_toys ( cost , N , K ) ) ;