给一个长度为 n n n 的序列 A 1 , A 2 , … , A n A_1,A_2,\dots ,A_n A1,A2,…,An,求存在 i , j i,j i,j使得 A i A i + 1 … A j 尽 量 大 A_iA_{i+1} \dots A_j 尽量大 AiAi+1…Aj尽量大
例题:Max Sum
Method_1 O ( N 3 ) O(N^3) O(N3)
暴力法
直接暴力搜索 i , j i,j i,j,并暴力搜索序列 A 1 , A 2 , … , A n A_1,A_2,\dots ,A_n A1,A2,…,An的和,遍历所有的可能性,寻找最大的序列和。
实现代码:
template<typename T>
void Max_sum1(T* array,int n){
int best=Minn; //the best result
int start1=0,end1=0;
for(int i=0;i<n;i++) //get the start
for(int j=i;j<n;j++){ //get the end
int number=0;
for(int k=i;k<=j;k++){
number=number+array[k];
}
if(best<number){
best=number;
start1=i;end1=j;
}
}
cout<<best<<" "<<start1+1<<" "<<end1+1<<endl;
}
Method_2 O ( N 2 ) O(N^2) O(N2)
优化一下Method_1,Method_1的复杂的为 O ( n 3 ) O(n^3) O(n3)。可以将最内层的for循环使用前缀和来替代,(有一种打表的思想)这样复杂的会将为 O ( n 2 ) O(n^2) O(n2)
template<typename T>
void Max_sum2(T* array,int n){
int best=Minn;
int start1=0,end1=0;
T s[100010]; //prefix sum
s[0]=0;
//get the prefix sum
for(int i=1;i<=n;i++)
s[i]=s[i-1]+array[i-1];
//find all combination of the i and j
for(int i=0;i<n;i++)
for(int j=i;j<n;j++){
int number=0;
if(best<s[j+1]-s[i]){
best=s[j+1]-s[i];
start1=i;end1=j;
}
}
cout<<best<<" "<<start1+1<<" "<<end1+1<<endl;
}
Method_3 O ( N ) O(N) O(N)
当 j j j确定时,目标为使得 s [ j ] − s [ i − 1 ] s[j]-s[i-1] s[j]−s[i−1]取得最大值,只需要将 s [ i − 1 ] s[i-1] s[i−1]取得最小值即可。
因此只需要便利一次数组,求得到当前位置的最小 s [ i − 1 ] s[i-1] s[i−1]即可。
template<typename T>
void Max_sum4(T* array,int n,int k){
int best=array[0]; //the first element
int start1=0,end1=0;
int s[100010];
s[0]=0;
//get the prefix sum
for(int i=1;i<=n;i++){
s[i]=s[i-1]+array[i-1];
}
//save the minimum s[i-1] when searching the list
int pre_min=0;
int start_point=1; //record the start_point
for(int i=1;i<=n;i++){
//the first time the best==s[i]-pre_min
//so the start1 and end1 must be change to 1
best=max(best,s[i]-pre_min);
if(best==s[i]-pre_min){
start1=start_point;
end1=i;
}
int previous=pre_min;
//if s[i]<0 the pre_min will be changed
pre_min=min(pre_min,s[i]);
if(pre_min==s[i]&&pre_min!=previous) start_point=i; //change the start
}
if(k-1) cout<<endl;
cout<<"Case "<<k<<":"<<endl;
cout<<best<<" "<<start1<<" "<<end1<<endl;
}
Method_4 O ( N ) O(N) O(N)
从前向后遍历,如果前方的某个前缀和小于0,则将整个前缀和全部舍弃,从该位置(作为起点)重新计算前缀和。
template<typename T>
void Max_sum5(T* array1,int n,int k){
int start=0,end=0;
int best=array1[0];//the first point,after that the i start from 1
int start_point=0;
//search the list from begin (i=1,because array1[i-1]) to end
for(int i=1;i<n;i++){
if(array1[i-1]>=0){
array1[i]=array1[i-1]+array1[i];
}else{
start_point=i; //change the start_point not the start
}
//judge whether to change the list
if(array1[i]>best){
best=array1[i];
start=start_point; //the start is the current start_point
end=i; //the end is current point i
}
}
if(k-1) cout<<endl;
cout<<"Case "<<k<<":"<<endl;
cout<<best<<" "<<start+1<<" "<<end+1<<endl;
}