Covering maximum array elements with given value | 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 code
function maxArrayCover ( a , n , x ) { a . sort ( ) ; let cc = 0 ; let s = 0 ; for ( let i = 0 ; i < n ; i ++ ) { s += a [ i ] ; if ( s > x ) { break ; } cc += 1 ; } var sum = a . reduce ( function ( a , b ) { return a + b ; } , 0 ) ; if ( sum == x ) { return n ; } else { if ( cc == n ) { return n - 1 ; } else { return cc ; } } } let n = 3 ; let x = 70 ; let a = [ 10 , 20 , 30 ] ; document . write ( maxArrayCover ( a , n , x ) ) ;