Python中的HackerRank“填充订单”问题

2024-09-25 08:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

最近,HackerRank推出了自己的认证。他们提供的测试包括“解决问题”。测试包含两个问题;他们给你90分钟来解决这些问题。由于我缺乏经验,我失败了,因为我花了更长的时间

具体地说,我在大约30分钟内为第一个问题(filled orders,见下文)找到了解决方案,并花了剩余的时间尝试调试它。它的问题不是解决方案不起作用,而是它只对一些测试用例起作用

在14个测试用例中,解决方案对7个(包括所有打开的和一堆关闭的)有效,对其余7个(所有关闭的)无效。关闭意味着输入数据和预期输出不可用。(这是有道理的,因为那里的一些列表包含250K+个元素。)

但它让我发疯;我想不出它有什么问题。我试着把print语句放得到处都是,但我得到的唯一结果是,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)

Tags: ofthein元素numberforif时间
3条回答

Python代码

    def filledOrders(order, k):
      orderfulfilled=0
      for i in range(1,len(order)):
        m=k-order[i]
        if(m>=0):
           orderfulfilled+=1
           k-=order[i]
      return(orderfulfilled)

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;

代码修订

def filledOrders(order, k):
  total = 0
  for i, v in enumerate(sorted(order)):
    if total + v <= k:
      total += v       # total stays <= k
    else:
      return i         # provides the count
  else:
    return len(order)  # was able to place all orders

print(filledOrders([3, 2, 1], 3))  # Out: 2
print(filledOrders([3, 2, 1], 1))  # Out: 1
print(filledOrders([3, 2, 1], 10)) # Out: 3
print(filledOrders([3, 2, 1], 0))  # Out: 0

相关问题 更多 >