Spiderman's Workout
InterviewTime limit1sMemory limit128 MB
Assign plus or minus signs to the distances so the partial sums stay at or above 0 and return to 0 at the end, minimizing the peak height.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Greedy, Implementation, Math
- Solved
- No attempts yet
Problem
Staying fit matters to every super hero, and Spiderman is no exception. Each day he does a climbing workout: he climbs a fixed distance, rests, climbs again, rests again, and so on. The workout is given as a sequence of distances , where is how many meters he moves up or down during the -th stage. For each stage it makes no difference to the workout whether he goes up or down, but he wants to choose a direction for every stage so that he both starts and finishes at street level (height 0). His feet may never go below street level.
He also wants to use as low a building as possible (secretly, he is afraid of heights). The building must be at least 2 meters taller than the highest point his feet reach during the workout.
Decide when he should go up and when he should go down so that the required building height is minimized. A valid climb must start and end at street level (0 meters), must never go below street level, and may not reorder the distances.
For example, with distances , going up, up, down, down needs a 42-meter building, while up, down, up, down needs only a 22-meter building and is optimal. Some sequences admit no valid climb at all (for instance ).
Input
The first line contains an integer , the number of scenarios. The next lines describe the scenarios, two lines each: the first line gives a positive integer , the number of distances, and the second line contains the positive integer distances separated by spaces. In any scenario the total of the distances is at most 1000.
Output
For each scenario output a single line. If a valid climb exists, output the minimum required building height (a single integer); otherwise output the string IMPOSSIBLE.