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