Maximize score of same | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxScoreSubArray ( int * a , int * b , int n ) { int res = 0 ; for ( int mid = 0 ; mid < n ; mid ++ ) { int straightScore = a [ mid ] * b [ mid ] , reverseScore = a [ mid ] * a [ mid ] ; int prev = mid - 1 , next = mid + 1 ; res = max ( res , 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 = max ( res , 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 = max ( res , max ( straightScore , reverseScore ) ) ; prev -- ; next ++ ; } } cout << res ; } int main ( ) { int A [ ] = { 13 , 4 , 5 } ; int B [ ] = { 10 , 22 , 2 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; maxScoreSubArray ( A , B , N ) ; return 0 ; }