Space-efficient algorithm for finding the largest balanced subarray?

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

    Sum all elements in the array, then diff = (array.length - sum) will be the difference in number of 0s and 1s.

    1. If diff is equal to array.length/2, then the maximum subarray = array.
    2. If diff is less than array.length/2 then there are more 1s than 0s.
    3. If diff is greater than array.length/2 then there are more 0s than 1s.

    For cases 2 & 3, initialize two pointers, start & end pointing to beginning and end of array. If we have more 1s, then move the pointers inward (start++ or end--) based on whether array[start] = 1 or array[end] = 1, and update sum accordingly. At each step check if sum = (end - start) / 2. If this condition is true, then start and end represent the bounds of your maximum subarray.

    Here we end up doing two passes of the array, once to calculate sum, and once which moving the pointers inward. And we are using constant space as we just need to store sum and two index values.

    If anyone wants to knock up some pseudocode, you're more than welcome :)

提交回复
热议问题