Finding the largest subarray with equal number of 0's and 1's

后端 未结 10 1950
我在风中等你
我在风中等你 2020-12-31 11:30

So, I have an array containing only 0\'s and 1\'s. I have to find out the largest subarray containing equal number of 0\'s and 1\'s. One can be a naive approach have complex

10条回答
  •  梦毁少年i
    2020-12-31 12:21

    Inspired from @templatetypedef algorithm i wrote code in python, hope it can be helpful for someone.

    def check_max_length(input_array):
        length = len(input_array)
        mapping_dict = {}
        max_length = 0
        for i in range(length):
            if input_array[i] not in mapping_dict.keys():
                mapping_dict[input_array[i]] = i
            else:
                max_length = max(max_length,i-mapping_dict[input_array[i]])
        return max_length
    
    def find_max_substring_length(input_string):
        def_array = [0]
        zero_count = 0
        one_count = 0
        # difference between number of zeroes and ones
        def_zero_one = 0
        for i in range(len(input_string)):
            if input_string[i] == '1':
                one_count+=1
            else:
                zero_count+=1
    
            def_array.append(one_count-zero_count)
        max_substring = check_max_length(def_array)
    return max_substring
    
    input_string = '1000100'
    substring_length = find_max_substring_length(input_string)
    print(substring_length) // will give result as 2
    

提交回复
热议问题