> For the complete documentation index, see [llms.txt](https://txfs19260817.gitbook.io/leetcode-go-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://txfs19260817.gitbook.io/leetcode-go-notes/solutions/325.-maximum-size-subarray-sum-equals-k.md).

# 325. Maximum Size Subarray Sum Equals k

## LeetCode [325. Maximum Size Subarray Sum Equals k](https://leetcode-cn.com/problems/maximum-size-subarray-sum-equals-k/)

### Description

Given an integer array `nums` and an integer `k`, return *the maximum length of a subarray that sums to* `k`. If there isn't one, return `0` instead.

**Example 1:**

```
Input: nums = [1,-1,5,-2,3], k = 3
Output: 4
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.
```

**Example 2:**

```
Input: nums = [-2,-1,2,1], k = 1
Output: 2
Explanation: The subarray [-1, 2] sums to 1 and is the longest.
```

**Constraints:**

* `1 <= nums.length <= 2 * 105`
* `-104 <= nums[i] <= 104`
* `-109 <= k <= 109`

### Tags

Hash Table

### Solution

This is a prefix-sum problem, combining LeetCode [560. Subarray Sum Equals K](/leetcode-go-notes/solutions/560.-subarray-sum-equals-k.md) and [525. Contiguous Array](/leetcode-go-notes/solutions/525.-contiguous-array.md). Note that we only record the map from prefix-sum to its index when such prefix-sum does not exist in the map, since we need the longest subarray.

### Complexity

* Time complexity: $$O(n)$$
* Space complexity: $$O(n)$$

### Code

```go
func maxSubArrayLen(nums []int, k int) int {
	ans, preSum, sum2idx := 0, 0, map[int]int{0: -1}
	for i, num := range nums {
		preSum += num
		if preIdx, ok := sum2idx[preSum-k]; ok {
			if ans < i-preIdx {
				ans = i - preIdx
			}
		}
		if _, ok := sum2idx[preSum]; !ok {
			sum2idx[preSum] = i
		}
	}
	return ans
}
```
