---
# System prepended metadata

title: Kadane's Algorithm
tags: [algorithm]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}
        /* 設定連結 */
a,
.open-files-container li.selected a {
    color: #89FFF8;
    
}
a:hover,
.open-files-container li.selected a:hover {
    color: #89FFF890;
}
   
</style>

###### tags: `algorithm`


# Kadane's Algorithm
### <a href="https://ithelp.ithome.com.tw/articles/10236541">資料來源</a>

## 概念
1. 如果目前元素陣列和 + 新數字大於新數字本身，則把新數字放進目前元素陣列和中。反之則以新數字當作新的開頭。(也就是目前陣列和大於零，繼續和新數字加總，反之將總和設為0+新數字 : Code II)
3. 記錄下目前元素陣列和大於最大值時，則把目前元素陣列賦值給最大值。
## Code I
```cpp=
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int max = nums[0], currentSum = 0;
        for(auto &it : nums){
            if(currentSum + it > it)
                currentSum += it;
            else
                currentSum = it;

            if(max < currentSum)
                max = currentSum;
        }
        return max;
    }
};
```
## Code II
```cpp=
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int maxSum = nums[0], currentSum = 0;
        for(auto &num : nums){
            currentSum = max(currentSum, 0) + num; 
            if(maxSum < currentSum)
                maxSum = currentSum;
        }
        return maxSum;
    }
};
```
## Practice
### <a href="https://hackmd.io/u_r8d9LyR2Gh95NMud3_vQ">53. Maximum Subarray</a>
### <a href="https://hackmd.io/lxFbGkAaRjySNhd9aBm3Cw">918. Maximum Sum Circular Subarray </a>