Covering maximum array elements with given value | Java 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
import java . util . * ; class GFG { public static int maxArrayCover ( int [ ] a , int n , int x ) { Arrays . sort ( a ) ; int cc = 0 ; int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) { s += a [ i ] ; if ( s > x ) { break ; } cc += 1 ; } if ( Arrays . stream ( a ) . sum ( ) == x ) { return n ; } else { if ( cc == n ) { return n - 1 ; } else { return cc ; } } } public static void main ( String [ ] args ) { int n = 3 ; int x = 70 ; int [ ] a = new int [ ] { 10 , 20 , 30 } ; System . out . println ( maxArrayCover ( a , n , x ) ) ; System . exit ( 0 ) ; } }