对序列{a} ,选择m个连续段,求总和最大
O(n^3)
const int N=1e3;
int a[N],s[N],n,m,f[N][N];
int sum(int i,int j){
return s[j]-s[i-1];
}
void solve(){
int i,j,k;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++){
f[i][j]=f[i-1][j];
for(k=0;k<i;k++){
f[i][j]=max(f[i][j],f[k][j-1]+sum(k+1,i));
}
}
cout<<f[n][m];
}
signed main(){
cin>>n>>m;
for(int i=1;i<=n;i++)
cin>>a[i],s[i]=s[i-1]+a[i];
solve();
}
O(n^2)
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std ;
const int N=1e3;
int a[N],n,m,f[N][N][2];
void solve(){
int i,j,k;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++){
f[i][j][0]=max(f[i-1][j][0],f[i-1][j][1]);
f[i][j][1]=max(f[i-1][j][1]+a[i],f[i-1][j-1][0]+a[i]);
}
cout<<max(f[n][m][0],f[n][m][1]);
}
signed main(){
cin>>n>>m;
for(int i=1;i<=n;i++)
cin>>a[i];
solve();
}