题目:连续子数组的最大和
要求:例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(6-3-2+7)。给一个数组,返回它的最大连续子向量的和.
class Solution { public: int FindGreatestSumOfSubArray(vector<int> array) { } };
解题代码:
class Solution { public: int FindGreatestSumOfSubArray(vector<int> array) { // 边界情况处理 if(array.size() == 0) return 0; if(array.size() == 1) return array[0]; // greatSum还可以设置为0x80000000代表最小负数(32位) int greatestSum = array[0]; int currentSum = 0; for(int i = 0; i < array.size(); i++){ if(currentSum <= 0) currentSum = array[i]; else currentSum += array[i]; // 更新和的最大值 if(currentSum > greatestSum) greatestSum = currentSum; } return greatestSum; } };