Get maximum items when other items of total cost of an item are free | Function to count the total number of items ; Sort the prices ; Choose the last element ; Initial count of item ; Sum to keep track of the total price of free items ; If total is less than or equal to z then we will add 1 to the answer ; Driver code
function items ( n , a ) { a . sort ( function ( a , b ) { return a - b } ) ; let z = a [ n - 1 ] ; let x = 1 ; let s = 0 ; for ( let i = 0 ; i < n - 1 ; i ++ ) { s += a [ i ] ; if ( s <= z ) x += 1 ; else break ; } return x ; } let n = 5 ; let a = [ 5 , 3 , 1 , 5 , 6 ] ; document . write ( items ( n , a ) ) ;