Java Solution-longest subarray that sums up to zero


  • 0
    F

    If we regard 0 as -1, then the problem is equivalent to finding the longest subarray that sums up to 0.

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

Log in to reply
 

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