#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define ll long long
#define mp make_pair
#define pb push_back
#define pii pair<int, int>
#define pll pair<ll, ll>
#define MASK(i) (1LL << (i))
#define BIT(x, i) (((x) >> (i)) & 1)
#define all(x) (x).begin() , (x).end()
#define TIME  (1.0 * clock() / CLOCKS_PER_SEC)
#define file "test" 
template <typename T1, typename T2> bool minimize(T1 &a, T2 b){if (a > b) {a = b; return true;} return false;}
template <typename T1, typename T2> bool maximize(T1 &a, T2 b){if (a < b) {a = b; return true;} return false;}
const int inf = 1e9;
const ll linf = 1e17;
const int mod = 1e9 + 7;
const int N = 1e6 + 5;
int n, k;
int a[N];
pll f[N];
ll pre[N];
ll res;
ll p;
void inp()
{
    cin >> n >> k;
    for(int i = 1; i <= n; ++i) cin >> a[i];
}
int opt(ll l) {
    for(int i = 1; i <= n; ++i) f[i] = {0, inf};
    ll idMx = 0;
    for(int i = 1; i <= n; ++i) {
        f[i].fi = f[i - 1].fi + pre[i - 1];
        f[i].se = f[i - 1].se;
        if(maximize(f[i].fi, f[idMx].fi + pre[i] - l))
            f[i].se = f[idMx].se + 1;
        f[i].fi -= pre[i];
        if(f[i].fi > f[idMx].fi) idMx = i;
    }
    return f[n].se;
}
void solve()
{
    for(int i = 1; i <= n; ++i) pre[i] = pre[i - 1] + 1ll * a[i];
    ll l = 0, r = 1e15;
    while(l <= r) {
        ll m = (l + r) >> 1;
        if(opt(m) <= k) {
            r = m - 1;
            p = m;
        }
        else l = m + 1;
    }
    // cout << p << '\n';
    ll x = opt(p);
    cout << f[n].fi + pre[n] + p * x;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    // freopen(file".inp" , "r" , stdin);
    // freopen(file".out" , "w" , stdout);
    inp();
    solve();
    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... |