Minimize the Sum of all the subarrays made up of the products of same-indexed elements

Given two arrays arr[] and arr2[] of length N, the task is to find the minimum sum of all the subarrays made up of the products of the same indexed elements of both the arrays after rearranging the second array.

Note: Since the answer can be very large, print the answer modulo 109 + 7.

Examples:

Input: arr[] = {1, 2}, arr2[] = {2, 3} 
Output: 14 
Explanation: 
Rearrange the arr2[] to {3, 2} 
Therefore, the product of same indexed elements of two arrays becomes {3, 4}. 
Possible subarrays are {3}, {4}, {3, 4} 
Sum of the subarrays = 3 + 4 + 7 = 14.
Input: arr[] = {1, 2, 3}, arr2[] = {2, 3, 2} 
Output: 43 
Explanation: 
Rearrange arr2[] to {3, 2, 2} 
Therefore, the product of thesame indexed elements of two arrays becomes {3, 4, 6}. 
Therefore, sum of all the subarrays = 3 + 4 + 6 + 7 + 10 + 13 = 43

Approach: 
It can be observed that, ith element occurs in (i + 1)*(n – i) subarrays. Therefore, the task is to maximize the sum of the (i + 1)*(n – i)* a[i] * b[i]. Follow the steps below to solve the problem: 
 



  • Since the elements of arr2[] can only be rearranged, so the value of (i + 1)*(n – i) * a[i] is constant for every ith element.
  • Therefore, calculate the value of the (i + 1)*(n – i)* a[i] for all the indices and then sort the products.
  • Sort the array arr2[] in descending order.
  • For every ith index, calculate the sum of the product of the values of (i + 1)*(n – i)* a[i] in descending order and arr2[i] in ascending order.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
#define ll long long
using namespace std;
 
const int mod = (int)1e9 + 7;
 
// Returns the greater of
// the two values
bool comp(ll a, ll b)
{
    if (a > b)
        return true;
    else
        return false;
}
 
// Function to rearrange the second array such
// that the sum of its product of same indexed
// elements from both the arrays is minimized
ll findMinValue(vector<ll>& a, vector<ll>& b)
{
 
    int n = a.size();
 
    // Stores (i - 1) * (n - i) * a[i]
    // for every i-th element
    vector<ll> pro(n);
 
    for (int i = 0; i < n; ++i) {
 
        // Updating the value of pro
        // according to the function
        pro[i] = ((ll)(i + 1) * (ll)(n - i));
        pro[i] *= (1LL * a[i]);
        ;
    }
 
    // Sort the array in revese order
    sort(b.begin(), b.end(), comp);
 
    // Sort the products
    sort(pro.begin(), pro.end());
 
    ll ans = 0;
    for (int i = 0; i < n; ++i) {
 
        // Updating the ans
        ans += (pro[i] % mod * b[i]) % mod;
        ans %= mod;
    }
 
    // Return the ans
    return ans;
}
 
// Driver code
int main()
{
 
    vector<ll> a = { 1, 2, 3 };
    vector<ll> b = { 2, 3, 2 };
    // Function call
    cout << findMinValue(a, b) << endl;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
static int mod = (int)1e9 + 7;
 
// Function to rearrange the second array such
// that the sum of its product of same indexed
// elements from both the arrays is minimized
static int findMinValue(int [] a, int []b)
{
    int n = a.length;
 
    // Stores (i - 1) * (n - i) * a[i]
    // for every i-th element
    int [] pro = new int[n];
 
    for(int i = 0; i < n; ++i)
    {
         
        // Updating the value of pro
        // according to the function
        pro[i] = ((i + 1) * (n - i));
        pro[i] *= (1L * a[i]);
        ;
    }
 
    // Sort the array in revese order
    Integer[] input = Arrays.stream(b).boxed(
                      ).toArray(Integer[]::new);
                       
    Arrays.sort(input, (x, y) -> y - x);
    b = Arrays.stream(input).mapToInt(
        Integer::intValue).toArray();
         
    // Sort the products
    Arrays.sort(pro);
 
    int ans = 0;
    for(int i = 0; i < n; ++i)
    {
         
        // Updating the ans
        ans += (pro[i] % mod * b[i]) % mod;
        ans %= mod;
    }
 
    // Return the ans
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int []a = { 1, 2, 3 };
    int []b = { 2, 3, 2 };
     
    // Function call
    System.out.print(findMinValue(a, b) + "\n");
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to implement
# the above approach
mod = 1e9 +7
 
# Function to rearrange
# the second array such
# that the sum of its
# product of same indexed
# elements from both
# the arrays is minimized
def findMinValue(a, b):
 
    n = len(a)
 
    # Stores (i - 1) * (n - i) * a[i]
    # for every i-th element
    pro = [0] * (n)
 
    for i in range (n):
 
        # Updating the value of pro
        # according to the function
        pro[i] = ((i + 1) * (n - i))
        pro[i] *= (a[i])
 
    # Sort the array in revese order
    b.sort(reverse = True)
 
    # Sort the products
    pro.sort()
 
    ans = 0
    for i in range (n):
 
        # Updating the ans
        ans += (pro[i] % mod * b[i]) % mod
        ans %= mod
    
    # Return the ans
    return ans
 
# Driver code
if __name__ == "__main__":
 
    a = [1, 2, 3]
    b = [2, 3, 2]
     
    # Function call
    print (int(findMinValue(a, b)))
 
# This code is contributed by Chitranayal

chevron_right


Output: 

43


 

Time Complexity: O(N log N)
Auxiliary Space: O(N)

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 : 29AjayKumar, chitranayal