vamsu
7/23/2018 - 10:14 PM

Find maximum length subarray with equal number of 1s and 0s

Find maximum length subarray with equal number of 1s and 0s

import java.util.*;
public class MaxSubArrayEqual1sAnd0s {
    public static void main(String args[]) {
        MaxSubArrayEqual1sAnd0s maxSubArray = new MaxSubArrayEqual1sAnd0s();
        int[][] input = {
          null,
          {},
          {0},
          {1},
          {1,0},
          {0,1,0},
          {0,0,1,0,1,0,0}
        };
        for(int i=0; i< input.length; i++) {
            System.out.println("Input: " + Arrays.toString(input[i]) + ", Result: " + Arrays.toString(maxSubArray.maxLengthArray(input[i])));
        }
    }
    
    public int[] maxLengthArray(int[] input) {
        if(input == null || input.length == 0) {
            return input;
        }
        // CurrentSum, Index
        Map<Integer, Integer> sumIndexTracker = new HashMap<>();
        // To address input array which begins with 0
        sumIndexTracker.put(0,-1);
        int currentSum = 0;
        int start = 0;
        int end = 0; 
        int maxLen = 0;
        for(int i=0; i< input.length; i++) {
            int currentValue = (input[i] == 0) ? -1:1;
            currentSum += currentValue;
            
            if(!sumIndexTracker.containsKey(currentSum)) {
                sumIndexTracker.put(currentSum, i);
            } else {
                if(maxLen < i - sumIndexTracker.get(currentSum)) {
                    start = sumIndexTracker.get(currentSum) + 1;
                    end = i;
                    maxLen = end - start + 1;
                }
            }
        }
        return extract(input, start, end);
    }
    
    private int[] extract(int[] input, int start, int end) {
        int[] extracted = new int[end - start + 1];
        int j = 0;
        for(int i=start; i<= end; i++) {
            extracted[j++] = input[i];
        }
        return extracted;
    }
}