Given an array nums and a target value K, find the maximum length of a subarray that sums to K. If there isn ' t one, return 0 instead. 1= [1,-1, 5,-2, 3], k = 3,return 4. (Because the Subarray [1,-1, 5,-2] sums to 32= [-2,-1, 2, 1], k = 1,return 2. (Because the Subarray [-1, 2] sums to 1 does it in O (n) time?
Like the other subarray sum problems lintcode:subarray sum closest
Use a HashMap to keep track of the sum from index 0 to index I, use it as the key, and use the current index as the value
Build the Hashmap:scan from left to write, if the current sum does not exist in the HashMap, put it in. If The current sum is does exist in Hashmap, does not replace or add to the older value, simply does not update. Because This value might is the left index of our Subarray in later comparison. We is looking for the longest subarray so we want the left index to be the smaller the better.
Every time we read a number in the array, we check to see if Map.containskey (num-k), if yes, try to update the MaxLen.
1 Public classSolution {2 Public intMaxsubarraylen (int[] Nums,intk) {3 if(nums==NULL|| nums.length==0)return0;4Hashmap<integer, integer> map =NewHashmap<integer, integer>();5Map.put (0,-1);6 intsum = 0;7 intMaxLen =Integer.min_value;8 for(inti=0; i<nums.length; i++) {9Sum + =Nums[i];Ten if(!map.containskey (sum)) { One map.put (sum, i); A } - if(Map.containskey (sum-k)) { - intindex = Map.get (sum-k); theMaxLen = Math.max (MaxLen, I-index); - } - } - returnMaxlen==integer.min_value? 0: MaxLen; + } -}
Leetcode:maximum Size subarray Sum Equals k