Saturday, 31 August 2013

Maximum purchased toys time out

Maximum purchased toys time out

So yeah, I have a homework sort of question which I've solved but keeps
giving a timeout error on test cases and I can't figure out why.
You need to buy your nephew toys for his birthday. But you only have
limited money. However, you want to buy as many unique toys as you can for
your nephew. Write a function that will return the max number of unique
toys you can buy.
The arguments to the functions are the integer array costs that contains
the costs for each toy and the integer budget which is the max amount of
money you can spend.
Return the integer representing the max number of unique toys you can buy
Constraints
If N is the number of toys and K is the budget... 1<=N<=105 1<=K<=109
1<=price of any toy<=109
Sample Input
costs: {1, 12, 5, 111, 200, 1000, 10} budget: 50 Sample Return Value
4 Explanation
He can buy only 4 toys at most. These toys have the following prices:
1,12,5,10.
so this is what I wrote and it keeps giving a timeout error on 10
testcases. I can't figure out why
function maxPurchasedToys(costs, budget) {
var costsLess=[];
var removeFromArray=function(arr, value){
for(i in arr){
if(arr[i]==value){
arr.splice(i,1);
break;
}
}
return costsLess;
}
//First let's get a new array consisting only of costs that are equal
to or below the budget
costs.map(function(x){x<budget?costsLess.push(x):1;})
var sum=0;
costsLess.map(function(x){sum+=x;});//Get the sum of budget
while(sum>=budget){
var max=Math.max.apply( Math, costsLess );
costsLess=removeFromArray(costsLess,max);//Remove the biggest
element to ensure that the costs fall within budget
sum=0;
costsLess.map(function(x){sum+=x;});//Get the new sum of budget
}
return costsLess.length;
}
I tried the following cases: the original test case, [5000,2000,20,200],50
and a few more. All executed fine

No comments:

Post a Comment