[LeetCode] 525. Contiguous Array
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.
Thought process:
Iterate through the array. Use a variable count to keep track of 0s and 1s. If I see a 1, increment count; Else, decrement count. The trick is that when I see two indices with the same count, the sub-array between them must have equal number of 0 and 1. Use a hash map of count -> index to keep track of this information.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Solution { public int findMaxLength(int[] nums) { Map<Integer, Integer> map = new HashMap<>(); map.put(0, -1); int count = 0; int max = 0; for (int i = 0; i < nums.length; i++) { count += nums[i] == 0 ? -1 : 1; if (map.containsKey(count)) { max = Math.max(i - map.get(count), max); } else { map.put(count, i); } } return max; } } |
Time complexity: O(n).
Comments
Post a Comment