最大子串和是一道经典的动态规划问题。
具体问题是指,在一串连续的数字中,找到一个最大的字串,它们的和在所有的子串中最大,
比如序列,6,-1,5,4,-7,它的连续最大段子串和就是:6 + (-1) + 5 + 4 = 14. 假设a[]为原始数据串。定义dp[i]为:以a[i]为结尾的最大子串和。
那么显然:递推式为:dp[i] = max{dp[i-1] + a[i] , a[i]}
#include <iostream>
#include <cstdio>
using namespace std;
int a[100000];
int main()
{
freopen("in.txt", "r", stdin);
int t;
cin >> t;
int i,j;
for (j = 0; j < t; j++)
{
int n;
cin >> n;
for (i = 0; i < n; i++)
cin >> a[i];
int s = 0,e = 0;
int start = 0;
int max = -100000000;
int tmp = 0;
for (i = 0; i < n; i++)
{
tmp += a[i];
if (tmp > max)
{
max = tmp;
s = start;
e = i;
}
if (tmp < 0)
{
start = i + 1;
tmp = 0;
}
}
cout << "Case " << j + 1 << ":" << endl;
cout << max << " " << s + 1 << " " << e + 1<< endl;
if (j != t - 1)
cout << endl;
}
return 0;
}