Maximize score of same | Function to calculate the score of same - indexed subarrays selected from the arrays a [ ] and b [ ] ; Store the required result ; Iterate in the range [ 0 , N - 1 ] ; Consider the case of odd length subarray ; Update the maximum score ; Expanding the subarray in both directions with equal length so that mid point remains same ; Update both the scores ; Consider the case of even length subarray ; Update both the scores ; Print the result ; Driver Code
function maxScoreSubArray ( a , b , n ) { let res = 0 ; for ( let mid = 0 ; mid < n ; mid ++ ) { let straightScore = a [ mid ] * b [ mid ] , reverseScore = a [ mid ] * a [ mid ] ; let prev = mid - 1 , next = mid + 1 ; res = Math . max ( res , Math . max ( straightScore , reverseScore ) ) ; while ( prev >= 0 && next < n ) { straightScore += ( a [ prev ] * b [ prev ] + a [ next ] * b [ next ] ) ; reverseScore += ( a [ prev ] * b [ next ] + a [ next ] * b [ prev ] ) ; res = Math . max ( res , Math . max ( straightScore , reverseScore ) ) ; prev -- ; next ++ ; } straightScore = 0 ; reverseScore = 0 ; prev = mid - 1 , next = mid ; while ( prev >= 0 && next < n ) { straightScore += ( a [ prev ] * b [ prev ] + a [ next ] * b [ next ] ) ; reverseScore += ( a [ prev ] * b [ next ] + a [ next ] * b [ prev ] ) ; res = Math . max ( res , Math . max ( straightScore , reverseScore ) ) ; prev -- ; next ++ ; } } document . write ( res ) ; } let A = [ 13 , 4 , 5 ] ; let B = [ 10 , 22 , 2 ] ; let N = A . length maxScoreSubArray ( A , B , N ) ;