Easy O(N) Java Solution Using HashMap


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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.