简体   繁体   中英

Python Maximum Pairwise Product time limit exceeded error

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)

When I submit the above code to Corsera's coding judge system,

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

has been returned. How can I change it?

It is in O(n^2). You can sort a and choose two larger value in a as a result in O(n log(n)) (if the input value for list a is positive).

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

首先以降序对项目进行排序,然后将已排序列表中的第一和第二项相乘(当然,如果所有结果都是肯定的),会不会花费更少的时间?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM