Java HashMap Solution


  • 0
    R
    public class Solution {
        public int maxSubArrayLen(int[] nums, int k) {
            if(nums.length == 0) return 0;
            int result;
            int[] dp = new int[nums.length+1];
            HashMap <Integer,Integer> hm = new HashMap<>();
            dp[0] = 0;
            hm.put(0,0);
            for(int i = 1; i < nums.length +1; i ++){
                dp[i] = dp[i-1] + nums[i-1];
                if(!hm.containsKey(dp[i])){
                    hm.put(dp[i],i);
                }
            }
            int maxLen = 0;int start = 0; int end = 0;
            for(int i = nums.length; i >=0; i --){
                int key = dp[i] - k;
                if(hm.containsKey(key)){
                    if(i>hm.get(key)&&(i - hm.get(key)) > maxLen){
                        start = hm.get(key);
                        end = i;
                        maxLen = end - start;
                    } 
                }
            }
            return maxLen;
            
        }
    }
    

Log in to reply
 

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