Maximum Size Subarray Sum Equals k(2sum和Map)
Example
Explanation:
because the subarray [1, -1, 5, -2] sums to 3 and is the longest.Explanation:
because the subarray [-1, 2] sums to 1 and is the longest.class Solution:
"""
@param nums: an array
@param k: a target value
@return: the maximum length of a subarray that sums to k
"""
def maxSubArrayLen(self, nums, k):
# Write your code here
presum = 0
dict = {0:-1}
ret = 0
for i, num in enumerate(nums):
presum += num
if presum not in dict:
dict[presum] = i
if presum - k in dict:
ret = max(i - dict[presum - k],ret)
return retLast updated