连续子数组的最大和
定义一个MaxSum存储最大值,定义一个currentSum存储当前最大值。当currentSum大于MaxSum时更新MaxSum,当currentSum<0时,则将currentSum记0,重新记录
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 5 int MaxSubArraySum(const vector<int>& data) 6 { 7 if (data.size() == 0) 8 return 0; 9 int MaxSum = 0; 10 int currentSum = 0; 11 for (int i = 0; i < data.size(); i++) 12 { 13 currentSum += data[i]; 14 if (currentSum > MaxSum) 15 MaxSum = currentSum; 16 else if (currentSum < 0) 17 currentSum = 0; 18 } 19 return MaxSum; 20 } 21 22 int main() 23 { 24 vector<int> data{ 1,-2,3,10,-4,7,2,-5 }; 25 cout << MaxSubArraySum(data) << endl; 26 return 0; 27 }