#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ull unsigned long long
#define ld long double
#define pii pair<int, int>
#define fi first
#define se second
#define __builtin_popcount __builtin_popcountll
#define all(x) (x).begin(), (x).end()
#define BIT(x, i) (((x) >> (i)) & 1)
#define MASK(x) ((1ll << (x)))
#define debug(a, l, r) for (int _i = (l); _i <= (r); ++_i) cout << (a)[_i] << ' '; cout << '\n';
const int MAXN = 3e5 + 5;
const int INF = 1e18 + 7;
int n, k, a[MAXN], pref[MAXN];
// int dp[MAXN][MAXN];
pii dp[MAXN][2];
pii check(int x) {
dp[1][0] = {0, 0};
dp[1][1] = {a[1] - x, 1};
for (int i = 2; i <= n; ++i) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]);
pii cand1 = {dp[i - 1][0].fi + a[i] - x, dp[i - 1][0].se + 1};
pii cand2 = {dp[i - 1][1].fi + a[i], dp[i - 1][1].se};
dp[i][1] = max(cand1, cand2);
}
return max(dp[n][0], dp[n][1]);
}
signed main() {
#ifdef NCTHANH
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(0);
cin.tie(nullptr); cout.tie(nullptr);
cin >> n >> k;
int cntneg = 0;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
if (a[i] < 0) ++cntneg;
pref[i] = pref[i - 1] + a[i];
}
if (cntneg == 0) {
cout << pref[n];
return 0;
}
if (k == 1) {
int pre = 0, res = 0;
for (int i = 1; i <= n; ++i) {
pre = min(pre, pref[i - 1]);
res = max(res, pref[i] - pre);
}
cout << res;
return 0;
}
if (cntneg == 1) {
int sum = 0;
for (int i = 1; i <= n; ++i)
if (a[i] >= 0) sum += a[i];
cout << sum;
return 0;
}
// for (int j = 1; j <= k; ++j) {
// int mx = -INF;
// for (int i = 1; i <= n; ++i) {
// dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
// mx = max(mx, dp[i - 1][j - 1] - pref[i - 1]);
// dp[i][j] = max(dp[i][j], mx + pref[i]);
// // for (int pre = i; pre >= 1; --pre) {
// // dp[i][j] = max(dp[i][j], dp[pre - 1][j - 1] + (pref[i] - pref[pre - 1]));
// // }
// }
// }
// cout << dp[n][k];
int l = 0, r = 1e15 + 5, ans = 0;
while (l <= r) {
int mid = (l + r) >> 1ll;
pii get = check(mid);
if (get.se >= k) {
l = mid + 1;
ans = mid;
} else r = mid - 1;
}
cout << check(ans).fi + k * ans;
return 0;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |