#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 4e18;
int N, K;
vector<ll> A;
pair<ll,int> solve(ll m) {
ll dp0 = 0, dp1 = -INF;
int c0 = 0, c1 = 0;
for (int i = 0; i < N; i++) {
ll x = A[i];
ll ndp1;
int nc1;
if (dp1 + x >= dp0 + x - m) {
ndp1 = dp1 + x;
nc1 = c1;
} else {
ndp1 = dp0 + x - m;
nc1 = c0 + 1;
}
ll ndp0;
int nc0;
if (dp0 >= dp1) {
ndp0 = dp0;
nc0 = c0;
} else {
ndp0 = dp1;
nc0 = c1;
}
dp0 = ndp0; c0 = nc0;
dp1 = ndp1; c1 = nc1;
}
if (dp0 >= dp1) return {dp0, c0};
return {dp1, c1};
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> N >> K;
A.resize(N);
for (int i = 0; i < N; i++) {
cin >> A[i];
}
ll lo = -1e12, hi = 1e12, bestm = 0;
while (lo <= hi) {
ll mid = (lo + hi) >> 1;
auto res = solve(mid);
if (res.second <= K) {
bestm = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
auto res = solve(bestm);
ll answer = res.first + bestm * K;
cout << answer << "\n";
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... |