# 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
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://txfs19260817.gitbook.io/leetcode-go-notes/solutions/325.-maximum-size-subarray-sum-equals-k.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
