Super Easy Java Solution, one loop


  • 0
    D
       Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int sum = 0, maxLength = 0;
        
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] == 0) {
                sum--;
            } else {
                sum++;
            }
            
            if(!map.containsKey(sum)) {
                map.put(sum, i);
            } else {
                maxLength = Math.max(maxLength, i - map.get(sum));
            }
    
        }
        
        return maxLength;

Log in to reply
 

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