超过Python最大成对产品时间限制

2024-09-29 23:24:27 发布

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

n = int(input())
a = [int(x) for x in input().split()]
product = 0
for i in range(n):
  for j in range(i + 1, n):
    product = max(product, a[i] * a[j])
print(product)

当我把上面的代码提交给Corsera的代码判断系统时

Failed case #4/17: time limit exceeded (Time used: 9.98/5.00, memory used: 20918272/536870912.)

已经归还。 我怎样才能改变它?你知道吗


Tags: 代码inforinput系统rangeproductmax
2条回答

是O(n^2)。您可以对a排序,并在a中选择两个较大的值作为O(n log(n))(如果list a的输入值为正)。你知道吗

input_list = sorted(a)
product = max(a[0]*a[1], a[-1] * a[-2]) #as suggested in comments if there is negative values

一开始按降序排序,然后从排序的列表中第一个和第二个相乘(当然,如果所有的都是正数的话),会不会花费更少的时间?你知道吗

相关问题 更多 >

    热门问题