Get maximum items when other items of total cost of an item are free | Java implementation of the above approach ; 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
import java . util . Arrays ; import java . io . * ; class GFG { static int items ( int n , int a [ ] ) { Arrays . sort ( a ) ; int z = a [ n - 1 ] ; int x = 1 ; int s = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { s += a [ i ] ; if ( s <= z ) x += 1 ; else break ; } return x ; } public static void main ( String [ ] args ) { int n = 5 ; int a [ ] = { 5 , 3 , 1 , 5 , 6 } ; System . out . println ( items ( n , a ) ) ; } }