所以,是的,我有一个家庭作业的问题,我已经解决了,但一直给测试用例一个超时错误,我不知道为什么。
你得给你侄子买玩具作为生日礼物。但你只有有限的钱。然而,你想为你的侄子购买尽可能多的独特玩具。编写一个函数,返回最大数量的独特玩具,你可以买。
函数的参数是整数数组成本,包含每个玩具的成本和整数预算,这是您可以花费的最大金额。
返回表示您可以购买的唯一玩具的最大数量的整数。
约束条件
如果N是玩具的数量,K是预算.1<=N<=105 1<=K<=109 1<=price of toy<=109
样本输入
费用:{1,12,5,111,200,1000,10}预算:50个样品返回值
4解释
他最多只能买4个玩具。这些玩具的价格如下: 1,12,5,10。
这就是我所写的,它总是给10个测试用例提供一个超时错误。我不知道为什么
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;
}我尝试了以下情况:最初的测试用例,5000,2000,20,200,50等等。全部执行罚款
发布于 2013-09-01 04:31:44
为什么不简单地排序和迭代呢?
function maxPurchasedToys (costs, budget) {
var i = 0, sum = 0, count = 0,
l = costs.length;
costs.sort(function (a, b) { return a - b });
while ( i < l ) {
if ( budget >= sum + costs[i] ) {
sum = sum + costs[i];
count++;
i++;
} else {
break;
}
}
return count;
}这是小提琴:http://jsfiddle.net/Ya5MK/
如果您能够使用ES5数组方法(您使用的是map,所以我猜您可以使用),请使用以下方法:
function maxPurchasedToys (costs, budget) {
var sum = 0, count = 0;
costs.sort(function (a, b) { return a - b }).some(function (cost) {
if ( budget >= sum + cost ) {
sum = sum + cost;
count++;
} else {
return true;
}
});
return count;
}这是小提琴:http://jsfiddle.net/Ya5MK/1/
发布于 2013-09-01 04:40:03
您可以尝试另一种方法,如排序,您的成本数组升序,并查看可以在该数组上获取多远。
sort.asp
function maxPurchasedToys (costs, budget) {
costs.sort(function(a,b){return a-b});
count = 0;
money = budget;
for (i=0; i<costs.length(); i++){
if (money > costs[i]){
money -= costs[i];
count ++;
}
else{
break;
}
}
return count;
}https://stackoverflow.com/questions/18555120
复制相似问题