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]);
}
if (n > 1) 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;
}