Title description
The largest sub-segment and question. Given a sequence consisting of n integers, find the maximum sum of sub-segments in the sequence. If all integers are negative integers, define the maximum sub-segment sum as 0.
Input format
Enter the number of integers n (1≤n≤1000) in the first line, and then input n integers in sequence.
Output format
Output the largest sub-segment sum.
Input sample
5
-2 11 -4 13 -5 -2
Sample output
20
AC code
#include <iostream>
using namespace std;
typedef long long ll;
const ll maxn = 10500;
ll a[maxn] = {
0},b[maxn] = {
0};
ll ans = -1000005;
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=n;i++){
if(i == 1){
b[i] = a[i];
}
else{
b[i] = max(b[i-1]+a[i],a[i]);
}
ans = max(ans,b[i]);
}
cout<<ans;
return 0;
}
Explanation
〇The largest subsection and the problem were mentioned twice in the previous blog post, but I encountered this problem again today. Since the problem was solved by referring to the previous blog post, I will post another blog post as a consolidation.
① The a[maxn] = {0},b[maxn] = {0};
a array is used to store the input elements, and the b array is used to record the local maximum sub-segment sum .
② core :
for(int i=1;i<=n;i++){
if(i == 1){
//如果是第一个元素,那么它本身就是局部最大子段和
b[i] = a[i];
}
else{
//否则,如果前面的子段和加上当前元素对局部最大子段和没有贡献,那么最大子段和
//为当前元素本身。(举个例子,之前的子段和为负数,显然加上它对最大子段和无贡献)
b[i] = max(b[i-1]+a[i],a[i]);
}
ans = max(ans,b[i]);//记录最大子段和
}
③Perfect AC.