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

后端 未结 10 1951
我在风中等你
我在风中等你 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条回答
  •  Happy的楠姐
    2020-12-31 12:17

    JS implementation of the @templatetypedef algorithm with a modification of using a map to help find the max length

    function findMaxLen(a) {
    // secondary array, initialized with the first element as 0
    let b = [0]
    let sum = 0
    
    // populate the secondary array and update the sum as per the algorithm
    for (let i = 0; i < a.length; i++) {
        b[i + 1] = a[i] == 0 ? sum - 1 : sum + 1
        sum = b[i + 1]
    }
    
    // map of sum vs the first index of the secondary array with the sum value
    let map = new Map()
    let maxLen = 0
    
    for (let i = 0; i < b.length; i++) {
        if (map.has(b[i]))
            maxLen = Math.max(maxLen, i - map.get(b[i]))
        else
            map.set(b[i], i)
    }
    
    return maxLen
    }
    

提交回复
热议问题