Maximum length of subarray with same sum at corresponding indices from two Arrays | 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
def maxLength ( A , B ) : NEW_LINE INDENT n = len ( A ) NEW_LINE maxSize = 0 NEW_LINE pre = { } NEW_LINE diff = 0 NEW_LINE pre [ 0 ] = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT diff += ( A [ i ] - B [ i ] ) NEW_LINE if ( not ( diff in pre ) ) : NEW_LINE INDENT pre = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT maxSize = max ( maxSize , i - pre + 1 ) NEW_LINE DEDENT DEDENT return maxSize NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 ] NEW_LINE B = [ 4 , 3 , 2 , 1 ] NEW_LINE print ( maxLength ( A , B ) ) NEW_LINE DEDENT