最近 HackerRank推出了自己的认证。他们提供的测试包括“问题解决”。测试包含2个问题;他们给你 90 分钟的时间来解决它们。由于我缺乏经验,我失败了,因为我花了比这更长的时间。
具体来说,我在大约 30 分钟内为第一个问题(已完成的订单,见下文)提出了解决方案,并用剩下的时间尝试调试它。它的问题不是解决方案不起作用,而是它仅适用于某些测试用例。
在 14 个测试用例中,该解决方案适用于 7 (包括所有开放的和一堆封闭的),以及 对剩余的 7 个无效 (全部关闭)。关闭意味着输入数据不可用,以及预期输出。 (这是有道理的,因为那里的一些列表包含 25 万多个元素。)
但它让我发疯;我无法弄清楚它可能有什么问题。我试着把打印语句到处都是,但我唯一发现的是,有 1 个太多的元素被添加到列表中——因此,最后一个 if
语句(删除最后添加的元素),但它没有任何区别,所以它可能是错误的。
这是问题所在:
A widget manufacturer is facing unexpectedly high demand for its new product,. They would like to satisfy as many customers as possible. Given a number of widgets available and a list of customer orders, what is the maximum number of orders the manufacturer can fulfill in full?
Function Description
Complete the function filledOrders in the editor below. The function must return a single integer denoting the maximum possible number of fulfilled orders.
filledOrders has the following parameter(s):
order : an array of integers listing the orders
k : an integer denoting widgets available for shipment
Constraints
1 ≤ n ≤ 2 x 105
1 ≤ order[i] ≤ 109
1 ≤ k ≤ 109
Sample Input For Custom Testing
2
10
30
40
Sample Output
2
这是我的功能:
def filledOrders(order, k):
total = k
fulf = []
for r in order:
if r <= total:
fulf.append(r)
total -= r
else:
break
if sum(fulf) > k:
fulf.pop()
return len(fulf)
最佳答案
Java解决方案
int count = 0;
Collections.sort(order);
for(int i=0; i<order.size(); i++) {
if(order.get(i)<=k) {
count++;
k = k - order.get(i);
}
}
return count;
关于python - Python 的 HackerRank "filled orders"问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61559308/