Maximum Size Subarray Sum Equals k

ArrayHash TablePrefix Sum
https://leetcode.com/problems/maximum-size-subarray-sum-equals-k

# Solution

# Brute Force

Complexity

time: O(n2)O(n^2)
space: O(1)O(1)

TLE

class Solution:
    def maxSubArrayLen(self, nums: List[int], k: int) -> int:
        # two pointers
        res = 0
        # lo, hi = 0, 0
        n = len(nums)
        for i in range(n):
            for j in range(i, n+1):
                if sum(nums[i:j]) == k and j - i > res:
                    res = j - i
        return res
1
2
3
4
5
6
7
8
9
10
11

# Prefix Sum + HashMap

Complexity

time: O(n)O(n)
space: O(n)O(n)

class Solution:
    def maxSubArrayLen(self, nums: List[int], k: int) -> int:
        res = 0
        psum = 0
        map = {0: -1}
        # map = {}
        n = len(nums)
        for i in range(n):
            psum += nums[i]

            # if psum == k:
            #     res = i + 1

            if (psum - k) in map:
                res = max(i - map[psum - k], res)

            if psum not in map:
                map[psum] = i

        return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20