Maximise the number of toys that can be purchased with amount K | Java Program to maximize the number of toys with K amount ; This functions returns the required number of toys ; sort the cost array ; Check if we can buy ith toy or not ; Increment count ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static int maximum_toys ( int cost [ ] , int N , int K ) { int count = 0 , sum = 0 ; Arrays . sort ( cost ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( sum + cost [ i ] <= K ) { sum = sum + cost [ i ] ; count ++ ; } } return count ; } public static void main ( String [ ] args ) { int K = 50 ; int cost [ ] = { 1 , 12 , 5 , 111 , 200 , 1000 , 10 , 9 , 12 , 15 } ; int N = cost . length ; System . out . print ( maximum_toys ( cost , N , K ) ) ; } }