#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N, K;
cin >> N >> K;
vector<ll> A(N);
for (int i = 0; i < N; i++) {
cin >> A[i];
}
// Case K = 1: maximum subarray sum (with empty allowed)
if (K == 1) {
ll max_ending = 0;
ll max_so_far = 0;
for (ll x : A) {
max_ending = max<ll>(0, max_ending + x);
max_so_far = max(max_so_far, max_ending);
}
cout << max_so_far << "\n";
return 0;
}
// Extract positive runs and gaps between them
vector<ll> runs;
vector<ll> gaps;
int i = 0;
while (i < N) {
// Skip non-positives
while (i < N && A[i] <= 0) {
i++;
}
if (i >= N) break;
// Collect positive run
ll sumP = 0;
while (i < N && A[i] > 0) {
sumP += A[i];
i++;
}
runs.push_back(sumP);
// Collect the gap (negatives) until next positive
ll sumG = 0;
int j = i;
while (j < N && A[j] <= 0) {
sumG += A[j];
j++;
}
if (j < N) {
gaps.push_back(sumG);
}
i = j;
}
int M = runs.size();
ll sumPos = 0;
for (ll v : runs) sumPos += v;
// If we have at least as many people as positive runs,
// we can assign each run to someone (others empty)
if (K >= M) {
cout << sumPos << "\n";
return 0;
}
// Need to merge (M-K) pairs by bridging across the least bad gaps
sort(gaps.begin(), gaps.end(), greater<ll>());
ll loss = 0;
int merges = M - K;
for (int t = 0; t < merges; t++) {
loss += gaps[t];
}
cout << (sumPos + loss) << "\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... |