Solution:
let dp[i][j] be the max sum of the previous j consecutive numbers divided into i groups,
of course end with a[j], then we consider whether put the j-th number into i-th group
if we do , that is dp[i][j-1] + a[j]
else we do not, then a[j] must be alone in one group ,which is the i-th group
so how about the previous i-1 groups and j-1 number ? we don’t really know how they
are grouped and what is the ending element of each group , but for dp[i][j] the previous
state can be dp[i-1][k],(0<k<j) for we don’t know the ending element of group i
so we can only enumerate the ending element for group i-1
the result of enumeration id max{dp[i-1][k]|0<k<j} ,by observation ,we can figure out this is
exactly the state dp[i][j] we calculated in the last outer for-cycle
let it be pre[j-1] we take the max index of k as its index
then the final state is pre[j-1] + a[j]
here it is
for(int i=1; i<=m; i++)
{
for(int j=i; j<=n; j++) //j start from i because each group has at least one element
{
dp[i][j]=max(dp[i][j-1] + a[j],last_dp[i][j](pre[j-1]) + a[j]
//update pre[j-1]
}
}
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn = 1e6+7;
int a[maxn],dp[maxn],pre[maxn];
int n,m,temp;
int main()
{
while(scanf("%d%d",&m,&n)!=EOF)
{
for(int i=1; i<=n; i++)
{
scanf("%d",a+i);
dp[i]=pre[i]=0;
}
for(int i=1; i<=m; i++)
{
temp=-INF;
for(int j=i; j<=n; j++)
{
dp[j]=max(dp[j-1]+a[j], pre[j-1] +a[j]);
/**
pre[j-1] is always updated after temp so is last max{dp[i-1][k]|0<k<j}
*/
pre[j-1]=temp;
temp=max(dp[j],temp);
}
}
///we should let max{dp[i]|1<=i<=n} be the answer ,but temp is already the max
printf("%d\n",temp);
}
return 0;
}