> For the complete documentation index, see [llms.txt](https://zcjian.gitbook.io/project/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zcjian.gitbook.io/project/array/subarray-sum-equals-k.md).

# Subarray Sum Equals K\*

```python
class Solution:
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        """
        背後原理:
        假設我們有 csumKey1 = cumulativeSum [i]為 nums[0] +...+ nums[i]的總和
        且我們現在有 csumKey2 = cumulativeSum[j]: nums[0] + ... + nums[i] + ... nums[j]
        若 csumKey2 - k = csumKey1 則我們可以宣稱找到一連續數和為 K
        註: 
        若array中的元素皆為"非負整數" 則我們可以說 nums[i+1]~ nums[j] 的累加值為 k
        若有負數則此法會無法知道 index 確切位置    
        
        Example: [3, 4, 7, 2, -3, 8] k = 7
        index:    1  2  3  4   5  6
        cSum:     3  7  14 16  11 19
                     ^ 
                  這裡我們意識預先給 csumKey = 0 的值: {0:1} 然後宣稱找到第一個累加值為7
        當 index = 3 時 我們把累加值減去 k : 14 - 7 = 7 然後去找是否有先前累加值為7的cSumkey
        我們找到先前 cSumKey = 7 (index = 2) 此時我們可以宣稱找到一連續subarray累加值為 7          
        """
        my_dict = {0:1}
        csum = 0
        res = 0
        for num in nums:
            csum += num            
            res += my_dict.get(csum-k, 0)
            my_dict[csum] = my_dict.get(csum, 0) + 1      
        return res
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://zcjian.gitbook.io/project/array/subarray-sum-equals-k.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
