DEV Community

codechunker
codechunker

Posted on

Solution to Leetcode's Contiguous Array

This is a medium Leetcode problem 525. See below image for description:

problem description

ALGORITHM

  1. Create a map that stores the current count to the index.
  2. Loop through the array, if the current value is 0, subtract 1 from count. if it is 1, add 1 to count.
  3. if the map does not have the current value of count as a key, put the new value in map with key as the current count and the value as the index.
  4. if the map has the current count as key, get the maximum between the current max and (index - value of the key).
  5. return max.

CODE

 public int findMaxLength(int[] nums) {
        int count = 0;
        int max = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0)
                count += -1;
            else
                count += 1;

            if (map.containsKey(count))
                max = Math.max(max, i - map.get(count));
            else
                map.put(count, i);

        }

        return max;
    }

Top comments (0)