📜  给定数组中所有有序对积的总和

📅  最后修改于: 2021-09-02 07:31:57             🧑  作者: Mango

给定一个大小为N的数组arr[] ,任务是找到可以从给定数组元素生成的有序对的所有乘积的总和。
例子:

朴素的方法:最简单的方法是遍历给定数组中的所有可能对,计算所有对产品的乘积之和。

时间复杂度: O(N 2 )
辅助空间: O(1)

高效的方法:上述方法可以基于以下观察进行优化:

请按照以下步骤解决问题:

  1. 初始化变量, res=0存放数组元素的总和
  2. 遍历数组arr[]并将数组的每个元素添加到res
  3. 最后,打印res的平方作为所需答案。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to calculate the
// sum of all pair-products
int sumOfProd(int arr[], int N)
{
    // Stores sum of array
    int sum = 0;
 
    for (int i = 0; i < N; i++) {
 
        // Update sum of the array
        sum += arr[i];
    }
 
    return sum * sum;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 1, 5, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << sumOfProd(arr, N);
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to calculate the
// sum of all pair-products
static int sumOfProd(int arr[], int N)
{
     
    // Stores sum of array
    int sum = 0;
 
    for(int i = 0; i < N; i++)
    {
         
        // Update sum of the array
        sum += arr[i];
    }
    return sum * sum;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 2, 3, 1, 5, 4 };
    int N = arr.length;
     
    System.out.print(sumOfProd(arr, N));
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program to implement
# the above approach 
 
# Function to calculate the
# sum of all pair-products
def sumOfProd(arr, N):
     
    # Stores sum of array
    sum = 0
 
    for i in range(N):
         
        # Update sum of the array
        sum += arr[i]
 
    return sum * sum
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 2, 3, 1, 5, 4 ]
    N = len(arr)
     
    print(sumOfProd(arr, N))
 
# This code is contributed by SURENDRA_GANGWAR


C#
// C# program to implement 
// the above approach  
using System;
 
class GFG{
     
// Function to calculate the 
// sum of all pair-products 
static int sumOfProd(int[] arr, int N) 
{ 
     
    // Stores sum of array 
    int sum = 0; 
   
    for(int i = 0; i < N; i++)
    {
         
        // Update sum of the array 
        sum += arr[i]; 
    } 
    return sum * sum; 
}  
 
// Driver code
static void Main()
{
    int[] arr = { 2, 3, 1, 5, 4 }; 
    int N = arr.Length; 
     
    Console.WriteLine(sumOfProd(arr, N));
}
}
 
// This code is contributed by divyeshrabadiya07


Javascript


输出:

225

时间复杂度: O(N)

辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live