# 0560. Subarray Sum Equals K

<https://leetcode.com/problems/subarray-sum-equals-k>

## Description

Given an array of integers `nums` and an integer `k`, return *the total number of continuous subarrays whose sum equals to `k`*.

**Example 1:**

```
**Input:** nums = [1,1,1], k = 2
**Output:** 2
```

**Example 2:**

```
**Input:** nums = [1,2,3], k = 3
**Output:** 2
```

**Constraints:**

* `1 <= nums.length <= 2 * 104`
* `-1000 <= nums[i] <= 1000`
* `-107 <= k <= 107`

## ac

similar: <https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/description/>

```java
class Solution {
    public int subarraySum(int[] nums, int k) {
        // edge cases
        if (nums == null || nums.length == 0) return 0;

        int count = 0;

        Map<Integer, Integer> map = new HashMap<>();
        map.put(0,1); // init
        int currSum = 0;
        for (int i = 0; i < nums.length; i++) {
            currSum += nums[i];
            int oldSum = currSum - k;
            count += map.getOrDefault(oldSum, 0);
            map.put(currSum, map.getOrDefault(currSum, 0) + 1);
        }

        return count;
    }
}
```


---

# 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://jaywin.gitbook.io/leetcode/solutions/0560-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.
