最大对明智乘积python

时间:2018-12-14 19:29:07

标签: python python-3.x

我实现了以下代码:

python3

n = int(input())
a = [int(x) for x in input().split()]
c = list()
for i in range(0,n):
    for j in range (1,n):
        if a[i] != a[j]:
            m = a[i]*a[j]
            c.append(m)

        else:
            continue

print(max(c))

输出错误

#4/17案例失败:超过了时间限制(使用时间:10.02 / 5.00,使用的内存:20910080/536870912。)

任何人都可以建议正确的代码以减少时间

1 个答案:

答案 0 :(得分:2)

如果您只是从给定列表中寻找两个元素的最大乘积,则无需对整个列表进行双重循环。您知道最大的乘积将是距离0最远且符号相同的那对数字的乘积。

# n is not actually needed in this case
n = int(input())

# sort the list
a = sorted([int(x) for x in input().split()])

# the largest product will either come from the last two numbers (if both are positive) or the first two (if both are negative)
print(max(a[-1]*a[-2], a[0]*a[1]))