Longest Span with same Sum in two Binary arrays | Java program to find largest subarray with equal number of 0 ' s ▁ and ▁ 1' s . ; 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
import java . io . * ; import java . util . * ; class GFG { static int longestCommonSum ( int [ ] arr1 , int [ ] arr2 , int n ) { int [ ] arr = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = arr1 [ i ] - arr2 [ i ] ; HashMap < Integer , Integer > hM = new HashMap < > ( ) ; int sum = 0 ; int max_len = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum == 0 ) max_len = i + 1 ; if ( hM . containsKey ( sum ) ) max_len = Math . max ( max_len , i - hM . get ( sum ) ) ; else hM . put ( sum , i ) ; } return max_len ; } public static void main ( String args [ ] ) { int [ ] arr1 = { 0 , 1 , 0 , 1 , 1 , 1 , 1 } ; int [ ] arr2 = { 1 , 1 , 1 , 1 , 1 , 0 , 1 } ; int n = arr1 . length ; System . out . println ( longestCommonSum ( arr1 , arr2 , n ) ) ; } }