题目链接 ~~~~~~
给出一个数组,你可以从这个数组中选一个区间,将区间内得所有数乘以X,求这个数组连续子数组的最大和。
首先,我们不难得出一个基本的算法设计,记数组dp[l][r][state]表示区间[l,r]状态为state时能获取的最大和,其中state表示我们是否已经乘过一个区间。但是这样复杂度太高,而且情况比较多,所以要对数组的表示进行优化。
记数组dp[pos][state]为有位置pos参与的区间中,状态为state时,最大区间和,其中state为0表示未选取区间,state为1表示位置pos正好位于选取区间中,state为2表示选取区间在位置pos前就已结束。
这样每一个元素都表示状态为state时,所有有pos参与区间中能得到的最大值,所以答案也就在这些元素当中
#include <stdio.h>
#include <climits>
#include <cstring>
#include <time.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <utility>
#include <vector>
#include <string>
#define INF 0x3f3f3f3f
#define ll long long
#define Pair pair<int,int>
#define re return
#define getLen(name,index) name[index].size()
#define mem(a,b) memset(a,b,sizeof(a))
#define Make(a,b) make_pair(a,b)
#define Push(num) push_back(num)
#define rep(index,star,finish) for(register int index=star;index<finish;index++)
#define drep(index,finish,star) for(register int index=finish;index>=star;index--)
using namespace std;
const int maxn=3e5+5;
int N,X;
ll store[maxn];
ll dp[maxn][3];
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cin>>N>>X;
store[0]=0;
rep(i,1,N+1){
cin>>store[i];
}
ll ans=0;
rep(i,0,3){
dp[0][i]=0;
}
rep(pos,0,N+1){
dp[pos+1][0]=max(dp[pos][0]+store[pos],store[pos]);
ans=max(ans,dp[pos+1][0]);
dp[pos+1][1]=max(max(dp[pos][0],dp[pos][1])+X*store[pos]*1LL,X*1LL*store[pos]);
ans=max(ans,dp[pos+1][1]);
dp[pos+1][2]=max(max(dp[pos][1],dp[pos][2])+store[pos],store[pos]);
ans=max(ans,dp[pos+1][2]);
}
cout<<ans<<endl;
re 0;
}