1007. Maximum Subsequence Sum (25)
Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1 <= i <= j <= K. TheMaximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.
Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.
Input Specification:
Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.
Output Specification:
For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.
Sample Input:10 -10 1 2 3 4 -5 -23 3 7 -21Sample Output:
10 1 4
题意:
1.输入一个正整数K;
2.输入K个整数
3.寻找子串和最大的子串,若不止有一个子串和最大,则选取位置靠前的子串
4.若K个数都是负数,那么输出子串和0,和数组第一个数及最后一个数
5.输出子串和,输出子串的第一个数和最后一个数。两数之间有空格,最后没有空格。
思路:
1.剔除数组首部和尾部的连续负数子串,缩小子串查找范围
2在l-h下标间,双重循环查找最大子串和
注意:
给出一个例子,我最后一次是死在这里
2
-1 0
输出应该是0 0 0
#include<iostream>
using namespace std;
int main()
{
int num;
int number[100000];
cin>>num;
for(int i=0;i<num;i++)
{
cin>>number[i];
}
int l=0;
while(number[l]<0)
{
l++;
if(l==num)
{
cout<<0<<" "<<number[0]<<" "<<number[num-1]<<endl;
return 0;
}
}
int h=num--;
while(number[h]<0)h--;
int max=0,max_i=0,max_j=0,ans=-1,ans_i=0,ans_j=0;
for(int i=l;i<=h;i++)
{
max_i=i;
for(int j=i;j<=h;j++)
{
max_j=j;
max+=number[j];
if(max>ans)
{
ans=max;
ans_i=max_i;
ans_j=max_j;
}
}
max=0;
max_i=0;
max_j=0;
}
cout<<ans<<" "<<number[ans_i]<<" "<<number[ans_j]<<endl;
return 0;
}