Loading

最大子列和问题

 

 

 

 

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 int MaxSubSum(int a[], int N)
 6 {
 7     int ThisSum = 0, MaxSum = 0;
 8     for(int i = 0; i < N; ++i)
 9     {
10         ThisSum += a[i];       //向右累加
11         if(ThisSum > MaxSum)
12             MaxSum = ThisSum;  //发现更大和则更新当前结果
13         else if(ThisSum < 0)   //若果当前子列和为负
14             ThisSum = 0;
15     }
16     return MaxSum;
17 }
18 
19 int main()
20 {
21     int K;
22     cin >> K;
23     const int N = K;
24     int a[N];
25     for(int i = 0; i < N; ++i)
26         cin >> a[i];
27     cout << MaxSubSum(a, N);
28 
29     return 0;
30 }

 

posted @ 2018-09-26 21:51  拾月凄辰  阅读(120)  评论(0编辑  收藏  举报