Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Max Over Feasible Candidates

The technique in one paragraph

When the problem asks for the $k$-th smallest / largest something, the direct question “is $X$ exactly at rank $k$?” is usually painful to check, because it tangles together counting and sort order. A cleaner attack is:

  1. Loosen the rank constraint: instead of “is $X$ the $k$-th?” ask the much weaker “is $X$ some part of some valid configuration?”. Call $X$ feasible if the answer is yes.
  2. Prove answer $=$ lex/value-max over feasible $X$ with the usual two directions:
    • Upper bound: the optimal $X$ is one of the parts of the optimal configuration, so it is feasible.
    • Lower bound: for any feasible $X$ we can explicitly construct a configuration with exactly $k$ parts containing $X$; among exactly $k$ parts the $k$-th sorted part is the maximum, which is $\ge X$.
  3. Enumerate candidates, check feasibility, take max.

You saw this technique on strings in Codeforces 2225F “String Cutting”. Below is the array analog for practice.


Exercise: Sum Cutting

You are given an array $a[1..n]$ of non-negative integers and integers $l, k$ with $1 \le l, k$ and $l \cdot k \le n$. Cut $a$ into $k$ or more contiguous subarrays, each of length $\ge l$. After sorting the subarrays by their sum in ascending order, maximize the $k$-th smallest sum.

If no valid partition exists (i.e. $l \cdot k > n$), output $-1$.

Constraints. $1 \le n \le 500$, $0 \le a_i \le 10^9$, $1 \le l, k \le n$.

Example. $n = 9$, $l = 2$, $k = 3$, $a = [3, 1, 4, 1, 5, 9, 2, 6, 5]$. One optimal partition:

  • $[3, 1]$ sum $= 4$
  • $[4, 1]$ sum $= 5$
  • $[5, 9, 2, 6, 5]$ sum $= 27$

Sorted sums: $4, 5, 27$. The $3$rd is $27$, which is the maximum achievable.

Try to solve it in $O(n^3)$ on your own before opening the hints.


Hints

The $k$-th sorted subarray in the optimal partition occupies some contiguous range $a[i..j]$. In any partition where $a[i..j]$ is a subarray, every other subarray lies entirely in $a[0..i-1]$ (left subarrays) or $a[j+1..n-1]$ (right subarrays).

Let there be $m$ left subarrays and $r$ right subarrays. Then $m + 1 + r \ge k$ and, because every subarray has length $\ge l$:

  • $m \cdot l \le i$ (so $m \le \lfloor i/l\rfloor$; $i = 0$ or $i \ge l$);
  • $r \cdot l \le n-1-j$ (so $r \le \lfloor (n-1-j)/l\rfloor$; $j = n-1$ or $j \le n-1-l$).

Don’t ask “can $a[i..j]$ be the $k$-th sorted subarray?” — that involves sort order and is hard.

Do ask “can $a[i..j]$ appear as some subarray (rank irrelevant) in some valid partition?” This is a pure counting question.

Call $(i, j)$ feasible iff:

  1. $j - i + 1 \ge l$;
  2. $i = 0$ or $i \ge l$;
  3. $n-1-j = 0$ or $n-1-j \ge l$;
  4. $\left\lfloor\dfrac{i}{l}\right\rfloor + \left\lfloor\dfrac{n-1-j}{l}\right\rfloor \ge k-1$.

Claim. $\displaystyle \text{answer} \;=\; \max\bigl\{\,\mathrm{sum}(a[i..j]) \,:\, (i,j)\text{ feasible}\,\bigr\}.$

Prove both directions.

Upper bound. The optimal $k$-th sorted subarray $a[i^*..j^*]$ is a subarray of the optimal partition, so $(i^*, j^*)$ is feasible, so $\mathrm{sum}(a[i^*..j^*]) \le$ max feasible sum.

Lower bound. For the arg-max feasible $(i^*, j^*)$, build a partition with exactly $k$ subarrays:

  • $m = \min(\lfloor i^*/l\rfloor, k-1)$ left subarrays covering $a[0..i^*-1]$, each of length $\ge l$;
  • $a[i^*..j^*]$ in the middle;
  • $r = k-1-m$ right subarrays covering $a[j^*+1..n-1]$, each of length $\ge l$.

Feasibility (condition 4) guarantees such $m, r$ exist. Total $=$ exactly $k$ subarrays, so the $k$-th sorted $=$ max $\ge$ candidate sum.

(The $k=2$ corner case with $i^* > 0$ and $j^* < n-1$ is handled as in problem F: at a lex/value max, the candidate can always be pushed to have $i^*=0$ or $j^*=n-1$, because since $a_i \ge 0$ extending a subarray only increases its sum.)

Precompute prefix sums $S[0..n]$ so that $\mathrm{sum}(a[i..j]) = S[j+1] - S[i]$ is computed in $O(1)$.

best = -1
for i in 0..n-1:
    if i != 0 and i < l: continue
    pre_cnt = i // l
    for j in i+l-1..n-1:
        suf = n-1-j
        if suf != 0 and suf < l: continue
        suf_cnt = suf // l
        if pre_cnt + suf_cnt < k - 1: continue
        s = S[j+1] - S[i]
        if s > best: best = s

print best
  • Outer pairs $(i,j)$: $O(n^2)$.
  • Per-pair work: $O(1)$ (thanks to prefix sums).
  • Total: $O(n^2)$.

(On strings we needed $O(n^3)$ because each lex comparison was $O(n)$; here the “comparison” is just comparing two integers in $O(1)$.)

For non-negative $a_i$, longer is always at least as good (extending a subarray cannot decrease its sum). So for fixed $i$, the best feasible $j$ is the maximum feasible $j$, namely

$$ \mathrm{rp}(i) = n - 1 - \max(k - 1 - \lfloor i/l\rfloor,\; 0)\cdot l. $$

That collapses the algorithm to $O(n)$ candidates, giving $O(n)$ total after prefix sums — identical to problem F’s O(n²) refinement, just with “sum” instead of “lex”.

If $a$ contains negative values, the “longer is better” step fails, but the $O(n^2)$ brute force from Hint 4 still works unchanged.


Editorial

Setup

Every subarray of the partition is $a[i..j]$ for some indices. If $a[i..j]$ is the $k$-th sorted, then besides it we have $m$ left subarrays in $a[0..i-1]$ and $r$ right subarrays in $a[j+1..n-1]$, each of length $\ge l$, with $m + r \ge k-1$.

Relaxation

Instead of “$a[i..j]$ is the $k$-th sorted”, ask “$a[i..j]$ is some subarray”. The feasibility condition becomes a pure counting one:

  1. $j - i + 1 \ge l$.
  2. $i \in \{0\}\cup[l,n-1]$.
  3. $n-1-j \in \{0\}\cup[l,n-1]$.
  4. $\lfloor i/l\rfloor + \lfloor (n-1-j)/l\rfloor \ge k-1$.

Main claim

$\text{answer} = \max_{(i,j)\text{ feasible}} \mathrm{sum}(a[i..j])$.

Upper bound. The optimal $k$-th sorted subarray $a[i^*..j^*]$ is itself a subarray of the optimal partition, hence $(i^*, j^*)$ is feasible.

Lower bound. For max-feasible $(i^*, j^*)$, construct a partition with exactly $k$ subarrays: $m$ left covering $[0, i^*-1]$, candidate, $r$ right covering $[j^*+1, n-1]$, with $m + r = k-1$ (possible by condition 4). Among exactly $k$ subarrays the $k$-th sorted is the max, which is $\ge$ the candidate’s sum.

Algorithm (O(n²))

long long best = -1;
vector<long long> S(n + 1, 0);
for (int t = 0; t < n; t++) S[t+1] = S[t] + a[t];

for (int i = 0; i < n; i++) {
    if (i != 0 && i < l) continue;
    long long pre_cnt = i / l;
    for (int j = i + l - 1; j < n; j++) {
        int suf = n - 1 - j;
        if (suf != 0 && suf < l) continue;
        long long suf_cnt = suf / l;
        if (pre_cnt + suf_cnt < k - 1) continue;
        best = max(best, S[j+1] - S[i]);
    }
}

Verifying on the example

$n=9, l=2, k=3, a=[3,1,4,1,5,9,2,6,5]$, $S = [0, 3, 4, 8, 9, 14, 23, 25, 31, 36]$.

We need $\lfloor i/2\rfloor + \lfloor (8-j)/2\rfloor \ge 2$, with appropriate prefix/suffix length checks. The feasible $(i, j)$ pair maximizing $S[j+1] - S[i]$ turns out to be $(4, 8)$:

  • $\lfloor 4/2\rfloor + \lfloor 0/2\rfloor = 2 + 0 = 2 \ge 2$. ✓
  • $\mathrm{sum}(a[4..8]) = 5+9+2+6+5 = 27$.

Matches the expected answer $27$. Partition: $[3,1]\,|\,[4,1]\,|\,[5,9,2,6,5]$ with sorted sums $4, 5, 27$.

Full reference code

See sol/code.


Variants to try next

Once you’re comfortable, try the same template on:

  1. Negative values allowed. The $O(n^2)$ from Hint 4 still works. The $O(n)$ refinement in Hint 5 fails; think about what it should be replaced by (hint: for fixed $i$, the optimal $j$ is the argmax of the prefix-sum function on $[i+l-1,\, \mathrm{rp}(i)]$; compute with a per-$i$ scan or with a suffix max of $S$).
  2. Minimize the $k$-th sorted sum instead of maximizing. Same technique, with $\min$ and a symmetric construction.
  3. Both sums and lengths as secondary keys. The feasibility condition is unchanged; only the “max” operator changes.

The technique generalises as long as two ingredients hold:

  • Feasibility of a candidate is easy to check (usually a counting inequality).
  • You can build a configuration with exactly $k$ parts containing any feasible candidate.