Description
Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:
Your task is to calculate d(A).
Input
The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, ..., an. (|ai| <= 10000).There is an empty line after each case.
Output
Print exactly one line for each test case. The line should contain the integer d(A).
Sample Input
1 10 1 -1 2 2 3 -3 4 -4 5 -5
Sample Output
13
考查点:动态规划
思路:求两段的最大子段和。可以分别求0~i和i~n这两段的最大子段和,再相加起来求出最值。第一次直接调用求子段的代码O(n),导致总时间为O(n^2)超时;后来用数组leftMax[i]保存0~i最大子段和,rightMax[i]保存i~n最大子段和,在O(n)时间内求出;再用O(n)时间求最值
代码:
#include <iostream>
#include <stdlib.h>
#define inf -300005
using namespace std ;
int main()
{
int t;
int n;
cin>>t;
while(t--)
{
cin>>n;
int * seq=new int[n];
int * leftMax=new int[n];
int * rightMax=new int[n];
for (int i=0;i<n;i++)
cin>>seq[i];
int result=inf;
int left=0;
int right=0;
int temp1=seq[0];
int temp2=seq[n-1];
leftMax[0]=seq[0];
rightMax[n-1]=seq[n-1];
for (int i=1;i<n;i++)
{
temp1=temp1+seq[i]>0?temp1+seq[i]:0;
leftMax[i]=leftMax[i-1]>temp1?leftMax[i-1]:temp1;
temp2=temp2+seq[n-i]>0?temp2+seq[n-i]:0;
rightMax[n-1-i]=rightMax[n-i]>temp2?rightMax[n-i]:temp2;
}
for (int s=0;s<n-1;s++)
{
left=leftMax[s];
right=rightMax[s+1];
// cout<<left<<" "<<right<<endl;
if (left+right>result)
result=left+right;
}
cout<<result<<endl;
}
return 0;
}
超时代码:
#include <iostream>
#include <stdlib.h>
#define inf -300005
using namespace std ;
int maxSequence(int * A,int start,int end)
{
int temp=0;
int max=inf;
if (start==end)
return A[start];
for (int i=start;i<=end;i++)
{
temp=temp+A[i]>0?temp+A[i]:0;
max=temp>max?temp:max;
}
return max;
}
int main()
{
int t;
int n;
cin>>t;
while(t--)
{
cin>>n;
int * seq=new int[n];
for (int i=0;i<n;i++)
cin>>seq[i];
int result=inf;
int left=0;
int right=0;
for (int s=0;s<n-1;s++)
{
left=maxSequence(seq,0,s);
right=maxSequence(seq,s+1,n-1);
if (left+right>result)
result=left+right;
}
cout<<result<<endl;
}
return 0;
}