【问题标题】:max pair wise product python最大对明智产品python
【发布时间】:2018-12-15 03:42:14
【问题描述】:

我实现了这段代码:

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。)

谁能提出正确的代码以减少时间

【问题讨论】:

  • edit你的问题包括你实际使用的代码print max(c))不会在任何版本的python上运行,因此不会超过任何超时。
  • 你能告诉我们实际的问题陈述吗?它可能会帮助我们为您找到答案。

标签: python python-3.x


【解决方案1】:

如果您只是从给定列表中寻找两个元素的最大乘积,则无需对整个列表进行双循环。您知道最大的乘积将是距离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]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多