Balls
Time limit1sMemory limit128 MB
There are n balls and n holes. Balls fall straight down from (i,h) to holes at (i,0). Placing exactly one obstacle (a segment between two integer columns) that tilts right redirects all balls in its column range to its right (lower) end; tilting left redirects them to its left (lower) end. For each orientation, maximize the total score over all valid placements (both orientations must be used, i.e., one obstacle of the specified tilt is mandatory, even if it reduces the total). Constraints n up to 3e5, c_i up to 1e9 in absolute value, so O(n log n) or O(n) required, answers in 64-bit.
- Level
Medium5 of 10
- Topics
- Array, Prefix sum, Greedy, Math
- Solved
- No attempts yet
Problem
There are balls and holes on a standard coordinate plane. The balls sit at positions for some height , and the holes are at . All balls are released at the same instant and fall straight down (in the negative direction). If a ball lands in the -th hole you earn points.
If nothing is done, ball falls into hole and the total is . To change the result you must place exactly one obstacle, which is a straight segment joining two integer columns:
- A right obstacle joins and with , and (it tilts down to the right, so its right end is the lower end).
- A left obstacle joins and with , and (it tilts down to the left, so its left end is the lower end).
When a falling ball touches the segment it stops, slides down to the lower end of the segment, and then drops straight into the hole directly beneath that lower end. Every ball whose column lies in the range is caught. Hence a right obstacle sends balls all into hole , and a left obstacle sends balls all into hole . After the obstacle is placed some holes may hold several balls and others none, but every ball still ends up in some hole.

Answer the following two questions:
- What is the highest score you can achieve if you must place exactly one right obstacle?
- What is the highest score you can achieve if you must place exactly one left obstacle?
Input
The first line contains one integer — the number of balls (which equals the number of holes). The second line contains space-separated integers — the values of the holes, listed from left to right.
Output
Print two lines. On the first line print a single integer: the highest achievable score when you must place exactly one right obstacle. On the second line print a single integer: the highest achievable score when you must place exactly one left obstacle. The answers can fall outside the 32-bit range, so use a 64-bit integer type.
Constraints
- .
- .
Note
Consider the sample with . The best right obstacle catches balls 3, 4, and 5 and drops them into hole 5, giving . The best left obstacle catches balls 2 through 6 and drops them into hole 2, giving . No other placement scores higher. Because an obstacle is mandatory, the required segment can lower the total when every possible placement is unfavorable.