Open In App

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

Last Updated : 05 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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 reverse 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;
}


Java




// 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 reverse 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


Python3




# 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 reverse 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


C#




// C# program to implement
// the above approach
using System;
using System.Linq;
using System.Collections.Generic;
 
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] *= (a[i]);
      ;
    }
 
    // Sort the array in reverse order
    List<int> input = new List<int>(b);
    input = input.OrderBy(inp => -inp).ToList();
 
    b = input.ToArray();
 
    // Sort the products
    Array.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
    Console.WriteLine(findMinValue(a, b) + "\n");
  }
}
 
// This code is contributed by phasing17


Javascript




<script>
 
// Javascript Program to implement
// the above approach
var mod = 1000000007;
 
// Function to rearrange the second array such
// that the sum of its product of same indexed
// elements from both the arrays is minimized
function findMinValue(a, b)
{
    var n = a.length;
 
    // Stores (i - 1) * (n - i) * a[i]
    // for every i-th element
    var pro = Array(n);
 
    for(var i = 0; i < n; ++i)
    {
         
        // Updating the value of pro
        // according to the function
        pro[i] = ((i + 1) * (n - i));
        pro[i] *= (1 * a[i]);
        ;
    }
 
    // Sort the array in reverse order
    b.sort((a, b) => b - a)
 
    // Sort the products
    pro.sort((a, b) => a - b)
 
    var ans = 0;
    for(var i = 0; i < n; ++i)
    {
         
        // Updating the ans
        ans += (pro[i] % mod * b[i]) % mod;
        ans %= mod;
    }
 
    // Return the ans
    return ans;
}
 
// Driver code
var a = [ 1, 2, 3 ];
var b = [ 2, 3, 2 ];
 
// Function call
document.write( findMinValue(a, b));
 
// This code is contributed by itsok
 
</script>


Output: 

43

 

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



Similar Reads

Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Maximize sum of product of same-indexed elements of equal length subarrays obtained from two given arrays
Given two arrays arr[] and brr[] of size N and M integers respectively, the task is to maximize the sum of the product of the same-indexed elements of two subarrays of an equal length with the selected subarray from the array brr[] being reversed. Examples: Input: arr[] = {-1, 3, -2, 4, 5}, brr[] = {4, -5}Output: 26Explanation:Subarrays selected fr
13 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Minimize sum of absolute differences of same-indexed elements of two given arrays by at most one replacement
Given two arrays A[] and B[] of size N each, the task is to find the minimum possible sum of absolute difference of same indexed elements of the two arrays, i.e. sum of |A[i] - B[i]| for all i such that 0 ? i &lt; N by replacing at most one element in A[] with another element of A[]. Examples: Input: A[] = {6, 4, 1, 9, 7, 5}, B[] = {3, 9, 7, 4, 2,
10 min read
Count pairs of same parity indexed elements with same MSD after replacing each element by the sum of maximum digit * A and minimum digits * B
Given an array arr[] of N 3-digit integers and two integers a and b, the task is to modify each array element according to the following rules: Find the maximum, say M, and minimum digit, say m, of each array element arr[i].Update the array element arr[i] as (A * M + B * m). The task is to count the number of pairs such that the chosen elements are
12 min read
Count N-length arrays made from first M natural numbers whose subarrays can be made palindromic by replacing less than half of its elements
Given two integer N and M, the task is to find the count of arrays of size N with elements from the range [1, M] in which all subarrays of length greater than 1 can be made palindromic by replacing less than half of its elements i.e., floor(length/2). Examples: Input: N = 2, M = 3Output: 6Explanation:There are 9 arrays possible of length 2 using va
4 min read
Make all the elements of array odd by incrementing odd-indexed elements of odd-length subarrays
Given an array arr[] of size N, the task is to make all the array elements odd by choosing an odd length subarray of arr[] and increment all odd positioned elements by 1 in this subarray. Print the count of such operations required. Examples: Input: arr[] = {2, 3, 4, 3, 5, 3, 2}Output: 2Explanation:In first operation, choose the subarray {2, 3, 4}
9 min read
Minimize cost of increments or decrements such that same indexed elements become multiple of each other
Given two arrays A[] and B[] consisting of N integers, the task is to minimize the total cost of incrementing or decrementing array elements by 1 such that for every ith element, either A[i] is a multiple of B[i] or vice-versa. Examples: Input: A[] = {3, 6, 3}, B[] = {4, 8, 13}Output: 4Explanation:Incrementing A[0] by 1 (3 + 1 = 4) makes it multipl
6 min read
Minimize swap between same indexed elements to make given Arrays strictly increasing
Given two arrays arr1[] and arr2[] of size N each, the task is to find the minimum number of interchange of the same indexed elements required to make both arrays strictly increasing. Note: Return -1 if it is not possible to make them strictly increasing. Examples: Input: arr1 = {1, 3, 5, 4}, arr2 = {1, 2, 3, 7}Output: 1Explanation: Swap arr1[3] an
10 min read
Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd
Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of the same indexed elements required to make the sum of the ASCII value of characters of both the strings odd. If it is not possible to make the sum of ASCII values odd, then print "-1". Examples: Input:S = ”acd”, T = ”dbf”Output: 1Exp
9 min read