I'm struggling to find an algorithm for this problem that runs in O(n) worst case time.
Let's say you have an array, of n elements, with the value of the elements being either 1 or 0. I need to calculate the number of sub-arrays where there exists more 1's inside the sub-array than there are 0's outside the sub-array.
what i tried to do:
i tried to first make a prefix-sum array of the input array, this is so that when given a sub-array, we grab the start and end indexes of the sub array, look at the corresponding values in the prefix array -> we can find out the number of 1s in the sub-array in O(n) time.
for example:
input array = [1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1]
prefix sum array = [0, 1, 1, 1, 2, 3, 3, 4, 4, 4, 5, 6, 6, 7]
example sub array = [1,0,0,1]
start index = 0, end index = 3
prefix[3+1] - prefix[0] = 2 - 0 = 2 (two 1s inside the sub
array)
I am not sure where to go from here. Help would be much appreciated.