CodeForces-1155D Beautiful Array(DP)

dp[i][0]:以a[i]结尾的最大字段和,前面先不考虑是不是以a[i]还是a[i]*x结尾
dp[i][1]:以a[i]*x结尾的最大字段和,考虑前面是以a[i]还是以a[i]*x结尾
dp[i][2]:以a[i]结尾的最大字段和,考虑前面是以a[i],a[i]*x或者前面的前面的以a[i],a[i]*x结尾

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=4*1e5;
ll  maxx,n,x,a[maxn],dp[maxn][5];
int main(){

    scanf("%lld%lld",&n,&x);
    for(ll i=1;i<=n;i++)
    {
        scanf("%lld",&a[i]);
    }
    maxx=0;
   // cout << maxx <<endl;
    for(int i=1;i<=n;i++)
    {
        dp[i][0]=max(dp[i-1][0]+a[i],a[i]);
        dp[i][1]=max(max(dp[i-1][1]+a[i]*x,dp[i-1][0]+a[i]*x),a[i]*x);
        dp[i][2]=max(max(max(dp[i-1][1]+a[i],dp[i-1][2]+a[i]),dp[i-1][0]+a[i]),a[i]);
        maxx=max(maxx,max(dp[i][0],max(dp[i][1],dp[i][2])));
        //cout << maxx <<endl;
    }
    cout <<maxx <<endl;
    return 0;
}

Description
You are given an array a consisting of n integers. Beauty of array is the maximum sum of some consecutive subarray of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0.

You may choose at most one consecutive subarray of a and multiply all values contained in this subarray by x. You want to maximize the beauty of array after applying at most one such operation.

Input
The first line contains two integers n and x (1≤n≤3⋅105,−100≤x≤100) — the length of array a and the integer x respectively.

The second line contains n integers a1,a2,…,an (−109≤ai≤109) — the array a.

Output
Print one integer — the maximum possible beauty of array a after multiplying all values belonging to some consecutive subarray x.

Examples
Input

5 -2
-3 8 -2 1 -6
Output

22
Input

12 -3
1 3 3 7 1 3 3 7 1 3 3 7
Output

42
Input

5 10
-1 -2 -3 -4 -5
Output

0
Solution
d1[i]:以a[i]结尾的最大子段和
d2[i]:a[i]被乘以x且以a[i]结尾的最大子段和
d3[i]:a[i]没有被乘以x,但在a[i]之前有一个区间被乘以x,以a[i]结尾且包含该区间的最大子段和
答案就是max(maxni=1(d1[i]),maxni=1(d2[i]),maxni=2(d3[i]))

猜你喜欢

转载自blog.csdn.net/w1304636468/article/details/89472270
今日推荐