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
const maxLength = ( A , B ) => { let n = A . length ; let maxSize = 0 ; let pre = { } ; let diff = 0 ; pre [ 0 ] = 0 ; for ( let i = 0 ; i < n ; i ++ ) { diff += ( A [ i ] - B [ i ] ) ; if ( ! ( diff in pre ) ) { pre = i + 1 ; } else { maxSize = Math . max ( maxSize , i - pre + 1 ) ; } } return maxSize ; } let A = [ 1 , 2 , 3 , 4 ] ; let B = [ 4 , 3 , 2 , 1 ] ; document . write ( maxLength ( A , B ) ) ;