Maximum Size Subarray Sum Equals k
要点:
- 为什么slinding window或者local ending at方法不行?要得到exact equals k,而array不是sorted。
- idea:基本利用了partial sum差得到subarray sum。另外因为要得到maxLen,所以从左到右scan的时候,相同的partial sum只记录最左边的即可(显然如果是minLen,记录最右)。
- sum_diff中作为减数的partial sum是exclusive的,所以长度公式是不+1的。同时也容易处理边界条件:初始化map为{0,-1}
- sum_diff只是右边的partial sum减去左边的,差值即为subarray sum,和结果正负无关
错误点:
- 注意减法的顺序:partial sum-k
class Solution(object):
def maxSubArrayLen(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
umap = {0:-1}
psum = 0
maxLen = 0
for i in xrange(len(nums)):
psum+=nums[i]
if psum-k in umap:
maxLen = max(maxLen, i-umap[psum-k])
if psum not in umap:
umap[psum]=i
return maxLen
sol = Solution()
assert sol.maxSubArrayLen([-2,-1,2,1], 1)==2, "max length is 2"