> For the complete documentation index, see [llms.txt](https://hannahpun.gitbook.io/leetcode-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hannahpun.gitbook.io/leetcode-note/math/53-maximum-subarray.md).

# #53 Maximum Subarray (有圖)

[LeetCode](https://leetcode.com/problems/maximum-subarray/)

```
Given an integer array nums, 
find the contiguous subarray (containing at least one number) 
which has the largest sum and return its sum.

out: 找找看相鄰的哪些加起來最大
```

```
Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:

If you have figured out the O(n) solution, 
try coding another solution using the divide and conquer approach, 
which is more subtle.
```

### Edge Case

* 只有一個就回傳那個值
* 會有負的喔

### 怎麼解

這題蠻值得思考的，我要鄰近數字加起來取 "最大值"，所以我可以自己跟前面比較取最大值

![](/files/-Lr2qvGGuk6gRCrC16y3)

![](/files/-Lr2r-5dVblbSOjEKBr-)

代表鄰近相加的總和，最後再取最大的，所以這個例子就是 6

```
var maxSubArray = function(nums) {
    if(nums.length < 2){
        return nums;
    }
    for(let i = 1; i < nums.length; i++){
        nums[i] = Math.max(nums[i], nums[i] + nums[i - 1])
    }
    return Math.max(...nums)
  

};
console.log(maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
```

### 學到什麼?

答案要什麼很重要，是一個值而已還是 Array，這題只要最大值所以我們不用去管是哪幾個相加起來只要著重在相加最大值是什麼就好了
