Maximum Size Subarray Sum Equals k

Problem: Maximum Size Subarray Sum Equals k

We can store an accumulated sum and get subarray sum by subtraction. If the accumulated sum at i+j minus sum at i equals k, we can say j is a potential size. Based on this idea, we can get a linear time solution.

Code in Python:

class Solution(object):
    def maxSubArrayLen(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        ans, acc = 0, 0
        dict = {0:-1}
        for i in xrange(len(nums)):
            acc += nums[i]
            if acc not in dict: dict[acc] = i
            if acc-k in dict: ans = max(ans, i-dict[acc-k])
        return ans

results matching ""

    No results matching ""