九度1011
最大连续子序列
-
题目描述:
-
给定K个整数的序列{ N1, N2, ..., NK },其任意连续子序列可表示为{ Ni, Ni+1, ..., Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个,例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和为20。现在增加一个要求,即还需要输出该子序列的第一个和最后一个元素。
-
输入:
-
测试输入包含若干测试用例,每个测试用例占2行,第1行给出正整数K( K< 10000 ),第2行给出K个整数,中间用空格分隔。当K为0时,输入结束,该用例不被处理。
-
输出:
-
对每个测试用例,在1行里输出最大和、最大连续子序列的第一个和最后一个元素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号i和j最小的那个(如输入样例的第2、3组)。若所有K个元素都是负数,则定义其最大和为0,输出整个序列的首尾元素。
-
样例输入:
-
6 -2 11 -4 13 -5 -2 10 -10 1 2 3 4 -5 -23 3 7 -21 6 5 -8 3 2 5 0 1 10 3 -1 -5 -2 3 -1 0 -2 0
-
样例输出:
-
20 11 13 10 1 4 10 3 5 10 10 10 0 -1 -2 0 0 0
只要找到加和过程中这里面的最大值即可。 复杂度为O(n^2) 效率不高
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int N;
int num[10000];
int maxBegin = 0;
int maxEnd = 0;
int currentBegin = 0;
int currentEnd = 0;
int max = -1;
int flag = 0;
while (true)
{
cin >> N;
maxBegin = 0;
maxEnd = 0;
currentBegin = 0;
currentEnd = 0;
max = -1;//☆☆☆☆☆☆注意这里一定要是 -1 要注意测试样例 3 -1 0 - 2 输出 0 0 0的特殊情况
flag = 0;
if (N == 0)
{
return 0;
}
for (int i = 0; i < N; i++)
{
cin >> num[i];
if (num[i]>=0)
{
flag = 1;
}
}
//
for (int i = 0; i < N; i++)
{
if (num[i]>=0)//
{
currentBegin = i;
currentEnd = i;
int j = i;
int currentValue = 0;
int currentMax = num[i];
while (currentValue >= 0 && j < N)
{
currentValue = currentValue + num[j];
if (currentValue>currentMax)
{
currentMax = currentValue;
currentEnd = j;
}
j++;
}
if (currentMax > max)
{
max = currentMax;///这里有问题
maxBegin = i;
maxEnd = currentEnd;
}
}
//小于0的开始必然不会作为最大值存在
}
if (flag == 0)
{
max = 0;
maxBegin = 0;
maxEnd = N - 1;
}
cout << max << " " << num[maxBegin] << " " << num[maxEnd] << endl;
}
return 0;
}