Get maximum items when other items of total cost of an item are free | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int items ( int n , int a [ ] ) { sort ( a , a + n ) ; 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 ; } int main ( ) { int n = 5 ; int a [ ] = { 5 , 3 , 1 , 5 , 6 } ; cout << items ( n , a ) ; }