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

后端 未结 10 1946
我在风中等你
我在风中等你 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条回答
  •  北海茫月
    2020-12-31 12:05

    Algorithm

    We make use of a HashMap map to store the entries in the form of (index,count). We make an entry for a count in the map whenever the count is encountered first, and later on use the corresponding index to find the length of the largest subarray with equal no. of zeros and ones when the same count is encountered again.

    public class Solution {
    
        public int findMaxLength(int[] nums) {
            Map map = new HashMap<>();
            map.put(0, -1);
            int maxlen = 0, count = 0;
            for (int i = 0; i < nums.length; i++) {
                count = count + (nums[i] == 1 ? 1 : -1);
                if (map.containsKey(count)) {
                    maxlen = Math.max(maxlen, i - map.get(count));
                } else {
                    map.put(count, i);
                }
            }
            return maxlen;
        }
    }
    
    
    
    
    
    Time complexity : O(n). The entire array is traversed only once.
    
    Space complexity : O(n). Maximum size of the HashMap map will be n, if all the elements are either 1 or 0.
    

提交回复
热议问题