Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
Example 2:
Note: The length of the given binary array will not exceed 50,000.
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Solution { public int findMaxLength(int[] nums) { int[] arr = new int[2 * nums.length + 1]; Arrays.fill(arr, -2); arr[nums.length] = -1; int maxlen = 0, count = 0; for (int i = 0; i < nums.length; i++) { count = count + (nums[i] == 0 ? -1 : 1); if (arr[count + nums.length] >= -1) { maxlen = Math.max(maxlen, i - arr[count + nums.length]); } else { arr[count + nums.length] = i; } } return maxlen; } } |
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.