/** * Given a binary array, find the maximum length of a contiguous subarray with * equal number of 0 and 1. * * Example 1: * Input: [0,1] * Output: 2 * * Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. * * Example 2: * Input: [0,1,0] * Output: 2 * * Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. * * Note: The length of the given binary array will not exceed 50,000. * */ public class ContiguousArray525 { /** * https://leetcode.com/problems/contiguous-array/solution/ */ public int findMaxLength(int[] nums) { int maxlen = 0; for (int start = 0; start < nums.length; start++) { int zeroes = 0, ones = 0; for (int end = start; end < nums.length; end++) { if (nums[end] == 0) { zeroes++; } else { ones++; } if (zeroes == ones) { maxlen = Math.max(maxlen, end - start + 1); } } } return maxlen; } public int findMaxLength2(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; } public int findMaxLength3(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; } }