Prefix Sum and Sliding Window 06
Given two binary arrays arr1[] and arr2[] of same size N. Find length of the longest common span [i, j] where j>=i such that arr1[i] + arr1[i+1] + .... + arr1[j] = arr2[i] + arr2[i+1] + .... + arr2[j].
Problem link :- click here
Code
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
// LONGEST SPAN IN TWO BINARY ARRAYS
public class Prefix_sum__Sliding_window_06
{
static int longestSpanInTwoBinaryArrays(int arr1[], int arr2[], int n)
{
int arr[] = new int[n];
// Initializing the array `arr`
for(int i=0; i<n; i++)
arr[i] = arr1[i] - arr2[i];
/*
METHOD: -
arr1 = {0, 1, 0, 0, 0, 0}
arr2 = {1, 0, 1, 0, 0, 1}
arr = arr1 - arr2
arr = {-1, 1, -1, 0, 0, -1}
psa = {-1, 0, -1, -1, -1, -2}
possible lengths: -
i) When sum == 0
maxLen = i + 1
= 1 + 1
= 2
ii) When hm.containsKey(sum)
maxLen = i - hm.get(sum)
a) = 2 - 0
= 2
b) = 3 - 0
= 3
c) = 4 - 0
= 4
Among all these possible lengths, the longest is 4.
*/
Map<Integer, Integer> hm = new HashMap<>();
int maxLen = 0;
int sum = 0;
for(int i=0; i<n; i++)
{
sum += arr[i];
if(sum == 0)
maxLen = i + 1;
if( hm.containsKey(sum) )
maxLen = Math.max(maxLen, i - hm.get(sum) );
else
hm.put(sum, i);
}
return maxLen;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// Taking size of array and array as input from the user
System.out.print("Enter the size of the array : ");
int n = s.nextInt();
int[] arr1 = new int[n];
System.out.println("Enter the array elements : ");
for(int i=0; i<n; i++)
arr1[i] = s.nextInt();
int[] arr2 = new int[n];
System.out.println("Enter the array elements : ");
for(int i=0; i<n; i++)
arr2[i] = s.nextInt();
int maxLen = longestSpanInTwoBinaryArrays(arr1, arr2, n);
System.out.println(maxLen);
}
}
Comments
Post a Comment