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 = 58Enter: 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++

Time complexity: O(N^{2})
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 precalculation 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++

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