<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: `Leetcode` # 53. Maximum Subarray ###### Link : https://leetcode.com/problems/maximum-subarray/description/ ## 題目 找到擁有最大加總的子陣列 <a href="https://hackmd.io/Pt-zqh8nT6O7cWfpKLtS9g?both">Kadane's Algorithm</a> ## 程式碼 ```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; } }; ``` NAMELY: ```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; } }; ```