Queries to multiply the given subarray with given number X and print sum

Given an array arr[] and Q queries where each query contains three integers (l, r, x), the task is to print the sum of the elements in range [l,r] after multiplying each element with x.
 

Query(l, r, x) = 
   arr[l]*x + arr[l+1]*x + .... arr[r-1]*x + arr[r]*x

Note: Multiplication with x is done to calculate the answer and it is not updated in the input array at any step of a query.
Examples: 
 

Input: arr[] = {2, 3, 4, 2, 5, 1} 
Q[] = {{2, 4, 5}, {1, 1, 4}} 
Output: 55 12 
Explanation: 
Query1: l = 2 r = 4 x = 5 
ans = arr[2]*5 + arr[3]*6 + ar[4]*7 
= 4*5 + 2*5 + 5*5 
= 55 
Query2: l = 1 r = 1 x = 4 
ans = arr[1]*4 
= 3*4 = 12
Input: arr[] = {2, 3, 4, 2} 
Q[] = {{1, 1, 8}} 
Output: 16 
Explanation: 
Query1: l = 1 r = 1 x = 8 
ans = arr[1]*8 
= 2*8 = 16 
 

 

Naive Approach: The idea is to iterate over each query of the array and for each query iterate over the elements of the [l, r] range and find the sum of each element multiplied by x. 
Time Complexity: O(Q*N)
Efficient Approach: The idea is to precompute the prefix sum of the array, then for each query find the sum of the elements of the range [l, r] and multiply by x to find the answer of each query. 
Below is the formulae to compute the answer of each query: 
 



// pre_sum[i] denotes the prefix sum of
// the array from the array 0 to i
answer = x * (pre_sum[r] - pre_sum[l-1])

Below is the implementation of the above approach: 
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to multiply
// the given subarray by the x
// for multiple queries of the Q
 
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to answer each query
int query(vector<int> pre_sum, int n,
         int l, int r, int val)
{
    int ans;
    int temp = 0;
    if (l > 0) {
        temp = pre_sum[l-1];
    }
    ans = val * (pre_sum[r] - temp);
    return ans;
}
 
// Function to multiply the subarray
// by the x for multiple Queries
void multiplyArray(int arr[],
 vector<pair<pair<int, int>, int>> q,
                             int n){
    vector<int> pre_sum;
    int s = 0;
     
    // Loop to compute the prefix
    // sum of the array
    for (int i = 0; i < n; i++){
        s += arr[i];
        pre_sum.push_back(s);
    }
     
    // Loop to answer each query
    for(auto i: q){
        cout << query(pre_sum, n, i.first.first,
         i.first.second, i.second) << endl;
    }
}
 
// Driver Code
int main()
{
    // Array
    int arr[] = { 2, 3, 4, 2, 5, 1 };
    int n = 6;
    vector<pair<pair<int, int>, int>> q;
    q.push_back({{2, 4}, 5});
    q.push_back({{1, 1}, 4});
    q.push_back({{1, 3}, -2});
     
    // Function Call
    multiplyArray(arr, q, n);
     
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to multiply
# the given subarray by the x
# for multiple queries of the Q
  
# Function to answer each query
def query(pre_sum, n, l, r, val):
 
    ans = 0
    temp = 0;
    if (l > 0):
        temp = pre_sum[l - 1];
     
    ans = val * (pre_sum[r] - temp);
    return ans;
   
# Function to multiply the subarray
# by the x for multiple Queries
def multiplyArray(arr, q, n):
     
    pre_sum = []
    s = 0;
      
    # Loop to compute the prefix
    # sum of the array
    for i in range(n):
 
        s += arr[i];
        pre_sum.append(s);
          
    # Loop to answer each query
    for i in q:
        print(query(pre_sum, n, i[0][0], i[0][1], i[1]))
         
# Driver Code
if __name__=='__main__':
 
    # Array
    arr = [ 2, 3, 4, 2, 5, 1 ]
    n = 6;
    q = []
    q.append([[2, 4], 5])
    q.append([[1, 1], 4])
    q.append([[1, 3], -2])
      
    # Function Call
    multiplyArray(arr, q, n);
      
# this code is contribute by rutvik_56

chevron_right


Output: 

55
12
-18

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : rutvik_56