# 最大连续子串和的逐步优化

start, end 记录最大连续子串和的头尾。

// O(n^3)
/*
三层循环， i, j 分别记录最大连续子串的头尾。
*/
int maxSubsequenceSum(int a[], int size, int &start, int &end)
{
int maxSum = 0;
for (int i = 0; i < size; ++i){
for (int j = i; j < size; ++j){
int currentSum = 0;
for (int k = i; k <= j; ++k){
currentSum += a[k];
if(currentSum > maxSum){
maxSum = currentSum;
start = i; end = j;
}
}
}
}
return maxSum;
}

// O(n^2)
/*
两层循环，sum(A[i]+...+A[j]) = A[j] + sum(A[i]+..+A[j-1]),
故可省略最里层的循环
*/
int maxSubsequenceSum(int a[], int size, int &start, int &end)
{
int maxSum = 0;
for(int i = 0; i < size; i++){
int currentSum = 0;
for(int j = i; j < size; j++){
currentSum += a[j];
if( currentSum > maxSum){
maxSum = currentSum;
start = i; end = j;
}
}
}
return maxSum;
}

// O(n)
/*
一层循环，使用 startTemp 记录可能构成最大连续子串的头，

关键： 若一个子序列的 和 是 负 的，则它不可能是最大连续子串的一部分。

如 { 1, -3, 4, -2, -1, 6 }， { 1, -3 }肯定不在最大连续子串中，
但 1 仍可能是最大子序列，注意保存该情况。
*/

int maxSubsequenceSum(int a[], int size, int &start, int &end)
{
int maxSum = 0;
int startTemp = 0;
int currentSum = 0;
start = end = 0;
for(int i = 0; i < size; i++){
currentSum += a[i];

if(currentSum < 0){
startTemp = i + 1;
currentSum = 0;
}
if(currentSum > maxSum){
maxSum = currentSum;
start = startTemp;
end = i;
}
}

return maxSum;
}

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=100005;
int a[maxn];

int maxSubsequenceSum(int a[], int &size, int &start, int &end)
{
int maxSum = 0;
int startTemp = 0;
int currentSum = 0;
for(int i = 0; i < size; i++){
currentSum += a[i];

if(currentSum < 0){
startTemp = i + 1;
currentSum = 0;
}

if(currentSum > maxSum){
maxSum = currentSum;
start = startTemp;
end = i;
}
}
return maxSum;
}

int main()
{
int t, n;
cin >> t;
for(int m = 1; m <= t; m++){
cin >> n;
int tag = 0;
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
if(a[i] > 0)
tag = 1;
}
cout << "Case " << m << ":" << endl;
int start = 0, end = 0, ans;
if(tag)//含有正数的情况
ans = maxSubsequenceSum(a, n, start, end);
else{//考虑全部非正的特殊情况
ans = a[0];
for(int i = 1; i < n; i++){
if(a[i] > ans){
ans = a[i];
start = i; end = i;
}
}
}
cout << ans <<" "<< start + 1 <<" "<< end + 1 << endl;
if(m != t)
cout << endl;
}
return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：最大连续子串和的逐步优化 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)