There are a number of different toys lying in front of him, tagged with their prices. Mark has only a certain amount to spend, and he wants to maximize the number of toys he buys with this money.
Given a list of prices and an amount to spend, what is the maximum number of toys Mark can buy? For example, if  and Mark has  to spend, he can buy items  for , or  for  units of currency. He would choose the first group of  items.

Sample Input
7  (Number of toys),  50 (the amount Mark has to spend).
1  12  5  111  200  1000  10 (Toys)
Sample Output
4  (An integer that denotes the maximum number of toys Mark can buy for his son).
Question from HackerRank.
Solution in C# -
class Programsaddaa { static int maximumToys(int[] prices, int k) {
 Array.Sort(prices); 
 int i; for(i=0; i<prices.Length && k>0; i++) {
 k -= prices[i]; 
 }
 return i-1; 
 } 
 static void Main(string[] args) {
 TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
 string[] nk = Console.ReadLine().Split(' ');
 int n = Convert.ToInt32(nk[0]);
 int k = Convert.ToInt32(nk[1]);
 int[] prices = Array.ConvertAll(Console.ReadLine().Split(' '), pricesTemp => Convert.ToInt32(pricesTemp)) ;
 int result = maximumToys(prices, k);
 textWriter.WriteLine(result);
 textWriter.Flush();
 textWriter.Close(); 
 }
 } 

Post a Comment

Previous Post Next Post