Find the maximum sum of the products in C++

Question

You are given two integer clusters arr and brr of length n. You can switch all things considered one subarray (constant subsegment) of cluster arr. Your errand is to oppose such arr subarray that the total ∑ni=1 (arri – brri ) is amplified.

Input :The principal line contains one integer n (1<=n<=5000). The subsequent line contains n integers arr1,arr2,…,arrn (1<=arri<=107). The third line contains n integers brr1,brr2,…,brrn (1<=brri<=107).

Output: Print single integer — greatest conceivable total subsequent to switching all things considered one subarray (persistent subsegment) of arr.

Summary

In this question, we have been given two arrays arr and brr of size n, and we have to find the maximum sum of products of elements of both the arrays, such that switching of the elements of the array is allowed. The maximum sum will be the answer and we have to print the output. We can achieve this output by using sorting techniques.

Explanation

Initially, we have taken two arrays arr and brr from the user along with their size n. As we want to find the maximum sum of the products, we have to multiply the maximum number of one array to the maximum number of the other array. So in this way, we will multiply sequentially the maximum number of one array corresponding to the maximum number of the other array. Like we will multiply the first maximum number of the first array to the first maximum number of the other array and the second maximum number of the first array to the second maximum number of the other array and so on. So in order to achieve the correct answer that is the maximum sum of the products, we will sort the array, and after sorting we will multiply the array elements correspondingly. at last, we will get the desired output.

Code

Code for the maximum sum of products in C++ is below.

#include<bits/stdc++.h>
using namespace std;

int maximumSumOfProducts(int arr[], int brr[], int n)
{
    /* to store the result */
    int sum = 0;
 
    /* sorting array arr */
    sort(arr,arr+n);
    
    /* sorting array brr */
    sort(brr,brr+n);
 
    /* to find the products and sum those products */
    for (int i = 0; i<n; i++)
        sum=sum+ arr[i]*brr[i];
 
    return sum;
}
int main()
{
    int n;
    cin>>n;
    int arr[n],brr[n];
    for(int i=0;i<n;i++)
    cin>>arr[i];
    for(int i=0;i<n;i++)
    cin>>brr[i];
    cout<<"\nMaximum sum of the products is: "<<maximumSumOfProducts(arr,brr,n)<<endl;
}

Output

Output for the maximum sum of products in C++ is below.

Find the maximum sum of the products in C++ output

 

 

Also read, Array of Function Pointer Exercises

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *