A maintenance crew monitors a pipeline instrumented with a row of n pressure sensors, numbered from the pipeline's inlet. Before a scheduled shutdown, the pipeline must be logically split into exactly three consecutive segments (in sensor order), and the first segment must start at the very first sensor. Recalibrating a segment costs exactly the pressure reading shown at the sensor where that segment begins. The crew wants to choose the two remaining split points -- cutting the line into 3 consecutive, non-empty segments -- to minimize the total recalibration cost, which is the sum of the three segments' opening readings.
Line 1: a single integer n -- the number of sensors.
Line 2: n space-separated integers reading[0], reading[1], ..., reading[n-1] -- the pressure reading at each sensor, in pipeline order.
Print a single integer: the minimum possible total recalibration cost over all ways to split the n sensors into exactly 3 consecutive, non-empty segments where the first segment begins at sensor 0.
3 <= n <= 500 <= reading[i] <= 50 for every valid iExample 1
Input
5 4 1 2 3 8
Expected
7
Explanation
The first segment must start at sensor 0 (reading 4), a fixed cost. Among sensors 1..4, the cheapest pair of split points has readings 1 (sensor 1) and 2 (sensor 2), so the total cost is 4+1+2 = 7. No other pair of split points does better.
Example 2
Input
3 5 5 5
Expected
15
Explanation
With n=3 there is only one possible way to form 3 non-empty segments: split points at sensor 1 and sensor 2. The cost is 5+5+5 = 15.
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 →