Monday, January 24, 2022
HomeSoftware DevelopmentDiscover the summation of the product of Array components in vary

Discover the summation of the product of Array components in vary [L, R]

Given an array arr[] and two integers L and R. The duty is to search out the sum of the product of all of the pairs (i, j) within the vary [L, R], such that i ≤ j.

Enter: arr[] = { 1, 3, 5, 8 }, L = 0, R = 2
Output: 58
Rationalization: As 1*1 + 1*3 + 1*5 + 3*3 + 3*5 + 5*5 = 58

Enter: arr[] = { 2, 1, 4, 5, 3, 2, 1 }, L = 1, R = 5
Output: 140

Naive Method: The brute drive strategy could be immediately carried out by multiplying the indices utilizing two nested loops and storing the sum in a variable.

Beneath is the implementation of the above strategy:

C++

 #embrace utilizing namespace std;    int sum_of_products(int arr[], int N, int L,                     int R) {     int sum = 0;        for (int i = L; i <= R; i++) {         for (int j = i; j <= R; j++) {             sum += arr[i] * arr[j];         }     }     return sum; }    int principal() {     int arr[] = { 1, 3, 5, 8 };     int N = sizeof(arr) / sizeof(arr);     int L = 0;     int R = 2;     cout << sum_of_products(arr, N, L, R);     return 0; }

Time complexity: O(N2)
Auxiliary House: O(1)

Environment friendly Method: This downside could be effectively solved by utilizing the Prefix sum method. On this methodology, retailer the prefix sum in pre-calculation after which iterate a single loop from L to R and multiply the corresponding prefix sum from that index to the final index.

Mainly 1*1+1*3+1*5+3*3+3*5+5*5 could be written as 1*(1+3+5)+3*(3+5)+5*(5) = 1*(prefix_sum from 1 to five)+3*(prefix_sum from 3 to five)+5*(prefix sum from 5 to five)

Beneath is the implementation of the above strategy.

C++

 #embrace utilizing namespace std;    int sum_of_products(int arr[], int n, int L,                     int R) {     int sum = 0;          int prefix_sum[n];     prefix_sum = arr;     for (int i = 1; i < n; i++) {         prefix_sum[i] = prefix_sum[i - 1]                         + arr[i];     }               for (int i = L; i <= R; i++) {                              if (i != 0)             sum += arr[i]                    * (prefix_sum[R]                       - prefix_sum[i - 1]);         else             sum += arr[i] * (prefix_sum[R]);     }     return sum; }    int principal() {     int arr[] = { 1, 3, 5, 8 };     int N = sizeof(arr) / sizeof(arr);     int L = 0;     int R = 2;     cout << sum_of_products(arr, N, L, R);     return 0; }

Time complexity: O(N)
Auxiliary House: O(N)

RELATED ARTICLES