I encountered this problem while preparing for my exams.
Given two arrays of numbers a1,..., an and b1,....,bn where each number is 0 or 1, the fastest algorithm to find the largest span (i,j) such that , ai + ai+1 +....+aj = bi + bi+1 +....+bj or report that there is not such span.
(A) Takes O(3^n) and omega(2^n) time if hashing is permitted.
(B) Takes O(n^3) and omega(n^2.5) and time in the key comparison mode
(C)Takes theta(n) time and space
(D)Takes O(square-root(n)) time only if the sum of 2n elements is an even number.
The only solution I can think of has O(n^2) and omega(n) time if anybody bothers to do the right check. It could probably be improved if anybody manages to find a way to take advantage of all values being 0 and 1.
int[] a = { 1, 1, 0, 1, 1, 0, 1, 0, 1 };
int[] b = { 0, 1, 0, 0, 1, 1, 0, 1, 0 };
int lastSum = 0; int lastI = 0; int lastJ = 0;
int sumA = 0; int sumB = 0;
for(int i = 0; i < a.Length; i++) // start the sum at [i].
{
sumA = a[i]; sumB = b[i];
for (int j = i + 1; j < a.Length; j++) // summing ends on [j]
//do
{
if (sumA == sumB && (lastJ - lastI < j - i))
{
lastSum = sumA;
lastI = i; lastJ = j;
if (j == a.Length - 1) // you will never find a bigger interval.
{
Console.Out.WriteLine("(i, j) = (" + lastI + ", " + lastJ + ")");
return;
}
}
sumA += a[j];
sumB += b[j];
}
}
Console.Out.WriteLine("(i, j) = (" + lastI + ", " + lastJ + ")");