Covering maximum array elements with given value | C ++ implementation of the approach ; Function to find value for covering maximum array elements ; sort the students in ascending based on the candies ; To store the number of happy students ; To store the running sum ; If the current student can 't be made happy ; increment the count if we can make the ith student happy ; If the sum = x then answer is n ; If the count is equal to n then the answer is n - 1 ; Driver function
# include <bits/stdc++.h> NEW_LINE using namespace std ; int maxArrayCover ( vector < int > a , int n , int x ) { sort ( a . begin ( ) , a . end ( ) ) ; int cc = 0 ; int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) { s += a [ i ] ; if ( s > x ) { break ; } cc += 1 ; } if ( accumulate ( a . begin ( ) , a . end ( ) , 0 ) == x ) { return n ; } else { if ( cc == n ) { return n - 1 ; } else { return cc ; } } } int main ( ) { int n = 3 ; int x = 70 ; vector < int > a = { 10 , 20 , 30 } ; printf ( " % d STRNEWLINE " , maxArrayCover ( a , n , x ) ) ; return 0 ; }