在最小的 Big O 中找到不同对的乘积之和

Find the sum of product of distinct pairs in lowest Big O

我想求最小大 O 中不同对的乘积之和。

列表 = [3、2、1、7、9]

所以不同的对将是 - (3,2) , (3,1) (3, 7), (3, 9) , (2, 1) , (2, 7), (2, 9) , (1, 7) , (1, 9) , (7, 9).

注意 - (2,3) 与 (3,2) 相同。

我在做什么:

   List = [3 , 2, 1 , 7, 9]

   int result = 0;

    for (int inner = 0; inner < list.size()-1; inner ++){

        for(int outer = inner+1; outer < list.size(); outer++){

            result+= list[inner] * list[outer];
        }
    }

它将在 O(n^2) 中 运行。

我想知道是否有更好的解决方案 运行 时间比 O(n^2) 更短。

谢谢。

编辑 - 不同对的总和 -> 不同对的乘积总和

我认为身份

(x1+x2+...+xn)^2 =
   x1^2+x2^2+...+xn^2
   +2(x1x2+...+x1xn+x2x3+...+x2xn+...)

这里是你的朋友。

您拥有高效的 O(n) 解决方案 here:

static int findProductSum(int A[], int n) 
{ 
    // calculating array sum (a1 + a2 ... + an) 
    int array_sum = 0; 
    for (int i = 0; i < n; i++) 
        array_sum = array_sum + A[i]; 

    // calcualting square of array sum 
    // (a1 + a2 + ... + an)^2 
    int array_sum_square = array_sum * array_sum; 

    // calcualting a1^2 + a2^2 + ... + an^2 
    int individual_square_sum = 0; 
    for (int i = 0; i < n; i++) 
        individual_square_sum += A[i] * A[i]; 

    // required sum is (array_sum_square - 
    // individual_square_sum) / 2 
    return (array_sum_square - individual_square_sum) / 2; 
} 

// Driver code 
public static void main(String[] args)  
{ 
    int A[] = {1, 3, 4}; 
    int n = A.length; 
    System.out.println("sum of product of all pairs of array "
            +"elements : " + findProductSum(A, n)); 
    } 
}