Space-efficient algorithm for finding the largest balanced subarray?

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

    Here's an actionscript solution that looked like it was scaling O(n). Though it might be more like O(n log n). It definitely uses only O(1) memory.

    Warning I haven't checked how complete it is. I could be missing some cases.

    protected function findLongest(array:Array, start:int = 0, end:int = -1):int {
        if (end < start) {
            end = array.length-1;
        }
    
        var startDiff:int = 0;
        var endDiff:int = 0;
        var diff:int = 0;
        var length:int = end-start;
        for (var i:int = 0; i <= length; i++) {
            if (array[i+start] == '1') {
                startDiff++;
            } else {
                startDiff--;
            }
    
            if (array[end-i] == '1') {
                endDiff++;
            } else {
                endDiff--;
            }
    
            //We can stop when there's no chance of equalizing anymore.
            if (Math.abs(startDiff) > length - i) {
                diff = endDiff;
                start = end - i;
                break;
            } else if (Math.abs(endDiff) > length - i) {
                diff = startDiff;
                end = i+start;
                break;
            }
        }
    
        var bit:String = diff > 0 ? '1': '0';
        var diffAdjustment:int = diff > 0 ? -1: 1;
    
        //Strip off the bad vars off the ends.
        while (diff != 0 && array[start] == bit) {
            start++;
            diff += diffAdjustment;
        }
    
        while(diff != 0 && array[end] == bit) {
            end--;
            diff += diffAdjustment;
        }
    
        //If we have equalized end. Otherwise recurse within the sub-array.
        if (diff == 0)
            return end-start+1;
        else
            return findLongest(array, start, end);      
    
    }
    

提交回复
热议问题