Space-efficient algorithm for finding the largest balanced subarray?

后端 未结 10 1171
谎友^
谎友^ 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:29

    linear time, constant space. Let me know if there is any bug I missed.
    tested in python3.

    def longestBalancedSubarray(A):
        lo,hi = 0,len(A)-1
        ones = sum(A);zeros = len(A) - ones
        while lo < hi:
            if ones == zeros: break
            else:
                if ones > zeros:
                    if A[lo] == 1: lo+=1; ones-=1
                    elif A[hi] == 1: hi+=1; ones-=1
                    else: lo+=1; zeros -=1
                else:
                    if A[lo] == 0: lo+=1; zeros-=1
                    elif A[hi] == 0: hi+=1; zeros-=1
                    else: lo+=1; ones -=1
        return(A[lo:hi+1])
    

提交回复
热议问题