Maximize Toys Geeks Solution Optimized
Problem : Given an integer depicting the amount with you. Maximize the number of toys you can have with K amount , arrays have cost of toys.
Solution : A greedy algo which first sorts the array and check for first i elements whose sum is less than k.
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
int k=ab.nextInt();
int i=0;
int count=0;
int arr[]=new int[n];
for(i=0;i<n;i++)
arr[i]=ab.nextInt();
Arrays.sort(arr);
i=0;
while(i<n && arr[i]<=k)
{
k-=arr[i++];
count++;
}
System.out.println(count);
}
}
}
0 Comments:
Post a Comment