# 53. Maximum Subarray

## 1.問題&#x20;

* 給予一個整數的array, 找出總和為最大值的連續subarray

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LN__HFQDfXcoazCKNt7%2F-LN__KSpXhFSXikIO-N7%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-29%20%E4%B8%8B%E5%8D%889.46.53.png?alt=media\&token=e09d19e1-3052-4f02-8227-f988a6081b00)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
  * 確認題意:  取得最大總和的subarray
* parameter
  * number list
* test input
* 說明想法
  * 由左邊開始移動, 計算subarray的總和
  * 記錄歷史的最大總和
  * 一旦總和小於0, 則讓總和歸零
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int ans = nums[0], i, j, sum=0;
        for(i = 0;i< (int)nums.size(); i++){
            sum += nums[i];
            ans = max(sum,ans);
            sum = max(sum,0);
        }
        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://jenhsuan.gitbook.io/algorithm/leetcode/53.-maximum-subarray.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.
