CodeForces-1155D Beautiful Array

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⋅10^5,−100≤x≤100)\) — the length of array \(a\) and the integer \(x\) respectively.

The second line contains \(n\) integers \(a_1,a_2,…,a_n\) \((−10^9≤ai≤10^9)\) — 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

  • \(d_1[i]\):以\(a[i]\)结尾的最大子段和
  • \(d_2[i]\)\(a[i]\)被乘以\(x\)且以\(a[i]\)结尾的最大子段和
  • \(d_3[i]\)\(a[i]\)没有被乘以\(x\),但在\(a[i]\)之前有一个区间被乘以\(x\),以\(a[i]\)结尾且包含该区间的最大子段和

答案就是\(\max\left(\max_{i=1}^{n}(d_1[i]), \max_{i=1}^{n}(d_2[i]),\max_{i=2}^{n}(d_3[i])\right)\)

转移方式在代码中:

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
  int n, k;
  scanf("%d%d", &n, &k);
  vector<ll> a(n), d1(n), d2(n), d3(n);
  for (int i = 0; i < n; ++i)
    scanf("%I64d", &a[i]);
  ll ans = 0;
  for (int i = 0; i < n; ++i) {
    d1[i] = a[i] + (i > 0 && d1[i - 1] > 0 ? d1[i - 1] : 0);
    ans = max(ans, d1[i]);
  }
  for (int i = 0; i < n; ++i) {
    d2[i] = k * a[i] + (i > 0 ? max(max(d2[i - 1], d1[i - 1]), 0LL) : 0);
    ans = max(ans, d2[i]);
  }
  ans = max(ans, d3[1] = a[0] * k + a[1]);
  for (int i = 2; i < n; ++i) {
    d3[i] = a[i] + max(d3[i - 1], d2[i - 1]);
    ans = max(ans, d3[i]);
  }
  printf("%I64d\n", ans);
  return 0;
}

猜你喜欢

转载自www.cnblogs.com/hitgxz/p/10754260.html