Contiguous Array

Problem:
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.
Analysis:
Mirror problem of Maximum size subarray sum equals k. When encounter 0, presum minus 1, when encounter 1, presum add 1.

Solution:


class Solution {
    public int findMaxLength(int[] nums) {
        int max = 0;
        Map<Integer, Integer> preSum = new HashMap<>();
        int sum = 0;
        preSum.put(0, -1);
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i] == 1 ? 1 : -1;
            if(preSum.containsKey(sum)) {
                max = Math.max(max, i - preSum.get(sum));
            }
            if (!preSum.containsKey(sum)) {
                preSum.put(sum, i);
            }
        }
        return max;
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array