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
< ? php function maxArrayCover ( $ a , $ n , $ x ) { sort ( $ a ) ; $ cc = 0 ; $ s = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ s += $ a [ $ i ] ; if ( $ s > $ x ) { break ; } $ cc += 1 ; } if ( array_sum ( $ a ) == $ x ) { return $ n ; } else { if ( $ cc == $ n ) { return $ n - 1 ; } else { return $ cc ; } } } $ n = 3 ; $ x = 70 ; $ a = array ( 10 , 20 , 30 ) ; echo maxArrayCover ( $ a , $ n , $ x ) ; ? >