A pipeline reports the net throughput (which may be negative) of each of n consecutive stages. A mandatory inspection happens at stage p (0-indexed), so any run you consider must include stage p.
Find the maximum sum over all non-empty contiguous runs that contain index p. This equals the best sum you can extend to the left of p (ending exactly at p) plus the best non-negative extension to the right of p. This is the "crossing run" combination at the heart of the divide-and-conquer maximum-subarray method, evaluated at a fixed anchor.
Line 1: two integers n and p (0-indexed anchor, 0 <= p < n).
Line 2: n space-separated integers, the per-stage throughputs.
A single integer: the maximum sum of a contiguous run that includes index p.
Example 1
Input
6 2 1 -2 3 -1 4 -5
Expected
6
Explanation
The best run through index 2 is 3, -1, 4 which sums to 6.
Example 2
Input
3 1 -5 -2 -8
Expected
-2
Explanation
The run must include index 1 (value -2); extending either way only lowers the total, so the best is -2.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →