Mark and Toys Solution in Javascript


Mark and Toys

Solution in Javascript

problem from Hackerrank.com

Problem

Mark and Jane are very happy after having their first kid. Their son is very fond of toys, so Mark wants to buy some. There are different toys lying in front of him, tagged with their prices, but he has only . He wants to maximize the number of toys he buys with this money.
Now, you are Mark's best friend and have to help him buy as many toys as possible.
Input Format
The first line contains two integers, and , followed by a line containing space separated integers indicating the products' prices

The key thing to the solution is just to sort toys.

 function processData(input) {  
   input = input.split('\n');  
   n = parseInt(input[0].split(' ')[0]);  
   money = parseInt(input[0].split(' ')[1]);  
   toys = input[1].split(' ').map(Number).sort((a,b)=>{return a-b});  
   //console.log('Toys sorted are '+toys);  
   let countToys = 0;  
   let moneyLeft = money;  
   let i = 0;  
   while(n-- && moneyLeft>0){  
     moneyLeft-=toys[i];  
     if(moneyLeft>=0){  
       countToys++;  
       //console.log('Buy item '+i +' with price '+toys[i]+' and moneyLeft = '+moneyLeft);  
       i++;  
     }  
     else{  
       break;  
     }  
   }  
   console.log(countToys);  
 }   
   
 process.stdin.resume();  
 process.stdin.setEncoding("ascii");  
 _input = "";  
 process.stdin.on("data", function (input) {  
   _input += input;  
 });  
   
 process.stdin.on("end", function () {  
   processData(_input);  
 });  
   
   

Σχόλια

Δημοφιλείς αναρτήσεις