Minimize the Sum of all the subarrays made up of the products of same | Java 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
import java . util . * ; class GFG { static int mod = ( int ) 1e9 + 7 ; static int findMinValue ( int [ ] a , int [ ] b ) { int n = a . length ; int [ ] pro = new int [ n ] ; for ( int i = 0 ; i < n ; ++ i ) { pro [ i ] = ( ( i + 1 ) * ( n - i ) ) ; pro [ i ] *= ( 1L * a [ i ] ) ; ; } Integer [ ] input = Arrays . stream ( b ) . boxed ( ) . toArray ( Integer [ ] :: new ) ; Arrays . sort ( input , ( x , y ) -> y - x ) ; b = Arrays . stream ( input ) . mapToInt ( Integer :: intValue ) . toArray ( ) ; Arrays . sort ( pro ) ; int ans = 0 ; for ( int i = 0 ; i < n ; ++ i ) { ans += ( pro [ i ] % mod * b [ i ] ) % mod ; ans %= mod ; } return ans ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 2 , 3 } ; int [ ] b = { 2 , 3 , 2 } ; System . out . print ( findMinValue ( a , b ) + "NEW_LINE"); } }