Maximum length of subarray with same sum at corresponding indices from two Arrays | C ++ program for the above approach ; Function to find maximum length of subarray of array A and B having equal sum ; Stores the maximum size of valid subarray ; Stores the prefix sum of the difference of the given arrays ; Traverse the given array ; Add the difference of the corresponding array element ; If current difference is not present ; If current difference is present , update the value of maxSize ; Return the maximum length ; Driver Code
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int maxLength ( vector < int > & A , vector < int > & B ) { int n = A . size ( ) ; int maxSize = 0 ; unordered_map < int , int > pre ; int diff = 0 ; pre [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { diff += ( A [ i ] - B [ i ] ) ; if ( pre . find ( diff ) == pre . end ( ) ) { pre = i + 1 ; } else { maxSize = max ( maxSize , i - pre + 1 ) ; } } return maxSize ; } int main ( ) { vector < int > A = { 1 , 2 , 3 , 4 } ; vector < int > B = { 4 , 3 , 2 , 1 } ; cout << maxLength ( A , B ) ; return 0 ; }