Maximum Size Subarray Sum Equals k
解析
class Solution(object):
def maxSubArrayLen(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
result = 0
hashmap = {}
sumValue = 0
for i in xrange(len(nums)):
sumValue += nums[i]
# 先判断从0到i的和是否等于k,因为从0到i的长度一定大于0到i中的一个subarray
if sumValue == k:
# 不能直接return,因为后边的subarray可能更长
result = i + 1
elif sumValue - k in hashmap:
result = max(result, i - hashmap[sumValue-k])
# 需要判断sumvalue的值是否存在,因为i要尽可能的在左边,确保result尽可能的长,例子[1,0,-1],k=-1,output=1(如果不加if),expected=2
if sumValue not in hashmap:
hashmap[sumValue] = i
return resultLast updated