Space-efficient algorithm for finding the largest balanced subarray?

后端 未结 10 1179
谎友^
谎友^ 2020-12-22 22:54

given an array of 0s and 1s, find maximum subarray such that number of zeros and 1s are equal. This needs to be done in O(n) time and O(1) space.

I have an algo whic

10条回答
  •  眼角桃花
    2020-12-22 23:43

    Different approach but still O(n) time and memory. Start with Neil's suggestion, treat 0 as -1.

    Notation: A[0, …, N-1] - your array of size N, f(0)=0, f(x)=A[x-1]+f(x-1) - a function

    If you'd plot f, you'll see, that what you look for are points for which f(m)=f(n), m=n-2k where k-positive natural. More precisely, only for x such that A[x]!=A[x+1] (and the last element in an array) you must check whether f(x) already occurred. Unfortunately, now I see no improvement over having array B[-N+1…N-1] where such information would be stored.

    To complete my thought: B[x]=-1 initially, B[x]=p when p = min k: f(k)=x . And the algorithm is (double-check it, as I'm very tired):

    fx = 0
    B = new array[-N+1, …, N-1]
    maxlen = 0
    B[0]=0
    for i=1…N-1 :
        fx = fx + A[i-1]
        if B[fx]==-1 :
            B[fx]=i
        else if ((i==N-1) or (A[i-1]!=A[i])) and (maxlen < i-B[fx]):
            We found that A[B[fx], …, i] is best than what we found so far
            maxlen = i-B[fx]
    

    Edit: Two bed-thoughts (= figured out while laying in bed :P ):

    1) You could binary search the result by the length of subarray, which would give O(n log n) time and O(1) memory algorithm. Let's use function g(x)=x - x mod 2 (because subarrays which sum to 0 are always of even length). Start by checking, if the whole array sums to 0. If yes -- we're done, otherwise continue. We now assume 0 as starting point (we know there's subarray of such length and "summing-to-zero property") and g(N-1) as ending point (we know there's no such subarray). Let's do

        a = 0
        b = g(N-1)
        while a

    Checking for subarray with "summing-to-zero property" of some given length L is simple:

        a = 0
        b = L
        fa = fb = 0
        for i=0…L-1:
            fb = fb + A[i]
        while (fa != fb) and (b

    2) …can you modify input array? If yes and if O(1) memory means exactly, that you use no additional space (except for constant number of elements), then just store your prefix table values in your input array. No more space used (except for some variables) :D

    And again, double check my algorithms as I'm veeery tired and could've done off-by-one errors.

提交回复
热议问题