Max Over Feasible Candidates
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:
- 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.
- 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$.
- Enumerate candidates, check feasibility, take max.
You saw this technique on strings in Codeforces 2225F “String Cutting”. Below is the array analog for practice.
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.
Once you’re comfortable, try the same template on:
- 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$).
- Minimize the $k$-th sorted sum instead of maximizing. Same technique, with $\min$ and a symmetric construction.
- 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.