首页 > 解决方案 > 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.)

已被退回。我怎样才能改变它?

标签: pythonalgorithm

解决方案


它在 O(n^2) 中。您可以在 O(n log(n)) 中排序a并选择两个较大的值a作为结果(如果列表的输入值为a正)。

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

推荐阅读