如果一个数组有[10,20,30,40]。我需要计算 10 *20+10*30+10*40+20*30+20*40+30*40。 假设乘法和加法都需要常数时间。 是否可以使用 O(n) 对其进行评估?
最佳答案
当然可以。
def sumproductsofpairs(lst):
total = 0
psum = 0
for x in lst:
total += psum * x
psum += x
return total
关于arrays - 所有数组元素对乘积的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25828445/