Suppose we have the array [1,2,3,4]
We want the amount of times where the sum of a contiguous subarray is for example in between l = 5
and u = 7
.
We can say this is the case for 1+2+3
, 3+4
So the answer would be 2
.
It is easily solved in O(n²) time, by using two for loops. Now how can this be solved in O(n log² n) time using a binary search tree? Negative values are included. Single values are also counted as a subarray.
My idea would be to loop over the left half of the array
i=0=> 1+5=6
1+7=8
i=1=> 2+5=7
2+7=9
Then use those values to perform a binary search in the right part (we sort the right part of the prefix sum) of the prefix sum array which would be
[1,3,6,10]
.
We try to find any of the values in the right part [6,10]
.
You can see the value 6 occurs in there. So the left bound is found. However the right bound is not found.
static int CountOverSplit(int[] prefixSum, int s, int m, int e, int lb, int ub, int[] input)
{
for (int i = s; i <= m; i++)
{
int lower = input[i] + lb;
int upper = input[i] + ub;
indexMinLeft = BinarySearchRecursive(prefixSum, lower, m, e - 1);
indexMaxRight = BinarySearchRecursive(prefixSum, upper, m, e - 1);
}
return indexMinLeft - indexMaxRight;
}
public static int BinarySearchRecursive(int [] inputArray, int key, int min, int max)
{
if (min > max)
{
return -1;
}
else
{
int mid = (min+max)/2;
if (key == inputArray [mid])
{
return ++mid;
}
else if (key < inputArray [mid])
{
return BinarySearchRecursive(inputArray, key, min, mid - 1);
}
else
{
return BinarySearchRecursive(inputArray, key, mid + 1, max);
}
}
}
I have been breaking my head over this for so long now, I really can't seem to figure it out.
Not sure if this belongs to stackoverflow or another stack, I'm sorry if it has been posted wrong. Thanks in advance. The question seems to be similar to this one, for reference.