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.
Example 1:
Given nums = [1, -1, 5, -2, 3]
, k = 3
,
Return 4
. (Because the Subarray sums to 3 and is the [1, -1, 5, -2]
longest)
Example 2:
Given nums = [-2, -1, 2, 1]
, k = 1
,
Return 2
. (Because the Subarray sums to 1 and is the [-1, 2]
longest)
Follow up:
Can do it in O (n) time?
Analysis:use a HashMap to store pair of <sum Val, Ind>, and then for each sum[i], we query whether there is <sum[i]- K, X>, if yes, then we found one candidate. Solution:
1 Public classSolution {2 Public intMaxsubarraylen (int[] Nums,intk) {3 intres = 0, Len =nums.length;4Map<integer,integer> Summap =NewHashmap<integer,integer>(); 5 6 intSum=0;7 for(inti=0;i<len;i++){8Sum + =Nums[i];9 if(sum==k) {Tenres = i+1; One}Else if(Summap.containskey (sum-k)) { Ares = Math.max (res, i-summap.get (sum-k)); - } - if(!summap.containskey (sum)) { the Summap.put (sum,i); - } - } - + returnRes; - } +}
Leetcode-maximum Size subarray Sum Equals k