Maximum length of subarray with same sum at corresponding indices from two Arrays | Java 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
import java . util . HashMap ; class GFG { public static int maxLength ( int [ ] A , int [ ] B ) { int n = A . length ; int maxSize = 0 ; HashMap < Integer , Integer > pre = new HashMap < Integer , Integer > ( ) ; int diff = 0 ; pre . put ( 0 , 0 ) ; for ( int i = 0 ; i < n ; i ++ ) { diff += ( A [ i ] - B [ i ] ) ; if ( ! pre . containsKey ( diff ) ) { pre . put ( diff , i + 1 ) ; } else { maxSize = Math . max ( maxSize , i - pre . get ( diff ) ) ; } } return maxSize ; } public static void main ( String args [ ] ) { int [ ] A = { 1 , 2 , 3 , 4 } ; int [ ] B = { 4 , 3 , 2 , 1 } ; System . out . println ( maxLength ( A , B ) ) ; } }