Java 37ms HashMap


  • 6
    H
    public int maxSubArrayLen(int[] nums, int k) {
            if(nums == null || nums.length == 0) return 0;
            int length = nums.length, sum = 0, maxSubLen = 0;
            //Using a hash map to store the sum of all the values before and include nums[i]
            Map<Integer, Integer> map = new HashMap();
            for(int i = 0; i < length; i++) {
                sum += nums[i];
                if(sum == k) {
                    maxSubLen = Math.max(maxSubLen, i + 1);
                } else if(map.containsKey(sum - k)) {
                    maxSubLen = Math.max(maxSubLen, i - map.get(sum - k));
                }
                
                if(!map.containsKey(sum)) {
                    map.put(sum, i);
                }
            }
            return maxSubLen;
        }

  • 0
    J
    if(sum == k) {
                maxSubLen = Math.max(maxSubLen, i + 1);
    }
    

    can just be "maxSubLen = i+1" since if sum == k, it will always be longer than the previous one.


  • 0
    S
    This post is deleted!

Log in to reply
 

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