Minimize sum of product of same | Function to print1 the arrays ; Function to reverse1 the subarray ; Function to calculate the minimum product of same - indexed elements of two given arrays ; Calculate initial product ; Traverse all odd length subarrays ; Remove the previous product ; Add the current product ; Check if current product is minimum or not ; Traverse all even length subarrays ; Remove the previous product ; Add to the current product ; Check if current product is minimum or not ; Update the poleters ; reverse1 the subarray ; print1 the subarray ; Driver Code
function print1 ( a , b ) { let minProd = 0 ; for ( let i = 0 ; i < a . length ; ++ i ) { document . write ( a [ i ] + " " ) ; } document . write ( " " ) ; for ( let i = 0 ; i < b . length ; ++ i ) { document . write ( b [ i ] + " " ) ; minProd += a [ i ] * b [ i ] ; } document . write ( " " ) ; document . write ( minProd ) ; } function reverse1 ( left , right , arr ) { while ( left < right ) { let temp = arr [ left ] ; arr [ left ] = arr [ right ] ; arr [ right ] = temp ; ++ left ; -- right ; } } function minimumProdArray ( a , b , l ) { let total = 0 ; for ( let i = 0 ; i < a . length ; ++ i ) { total += a [ i ] * b [ i ] ; } let min = Number . MAX_SAFE_INTEGER ; let first = 0 ; let second = 0 ; for ( let i = 0 ; i < a . length ; ++ i ) { let left = i - 1 ; let right = i + 1 ; let total1 = total ; while ( left >= 0 && right < a . length ) { total1 -= a [ left ] * b [ left ] + a [ right ] * b [ right ] ; total1 += a [ left ] * b [ right ] + a [ right ] * b [ left ] ; if ( min >= total1 ) { min = total1 ; first = left ; second = right ; } -- left ; ++ right ; } } for ( let i = 0 ; i < a . length ; ++ i ) { let left = i ; let right = i + 1 ; let total1 = total ; while ( left >= 0 && right < a . length ) { total1 -= a [ left ] * b [ left ] + a [ right ] * b [ right ] ; total1 += a [ left ] * b [ right ] + a [ right ] * b [ left ] ; if ( min >= total1 ) { min = total1 ; first = left ; second = right ; } -- left ; ++ right ; } } if ( min < total ) { reverse1 ( first , second , a ) ; print1 ( a , b ) ; } else { print1 ( a , b ) ; } } let n = 4 ; let a = [ 2 , 3 , 1 , 5 ] ; let b = [ 8 , 2 , 4 , 3 ] ; minimumProdArray ( a , b , n ) ;