Longest Span with same Sum in two Binary arrays | Returns largest common subarray with equal number of 0 s and 1 s ; Find difference between the two ; Creates an empty hashMap hM ; Initialize sum of elements ; Initialize result ; Traverse through the given array ; Add current element to sum ; To handle sum = 0 at last index ; If this sum is seen before , then update max_len if required ; Else put this sum in hash table ; Driver code
def longestCommonSum ( arr1 , arr2 , n ) : NEW_LINE INDENT arr = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = arr1 [ i ] - arr2 [ i ] ; NEW_LINE DEDENT hm = { } NEW_LINE sum = 0 NEW_LINE max_len = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE if ( sum == 0 ) : NEW_LINE INDENT max_len = i + 1 NEW_LINE DEDENT if sum in hm : NEW_LINE INDENT max_len = max ( max_len , i - hm [ sum ] ) NEW_LINE DEDENT else : NEW_LINE INDENT hm [ sum ] = i NEW_LINE DEDENT DEDENT return max_len NEW_LINE DEDENT arr1 = [ 0 , 1 , 0 , 1 , 1 , 1 , 1 ] NEW_LINE arr2 = [ 1 , 1 , 1 , 1 , 1 , 0 , 1 ] NEW_LINE n = len ( arr1 ) NEW_LINE print ( longestCommonSum ( arr1 , arr2 , n ) ) NEW_LINE