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
< ? php function items ( $ n , $ a ) { sort ( $ a ) ; $ z = $ a [ $ n - 1 ] ; $ x = 1 ; $ s = 0 ; for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) { $ s += $ a [ $ i ] ; if ( $ s <= $ z ) $ x += 1 ; else break ; } return $ x ; } $ n = 5 ; $ a = array ( 5 , 3 , 1 , 5 , 6 ) ; echo items ( $ n , $ a ) ; ? >