Departmental Deficiency
Director Cheeseburger has encountered a systemic risk to AUCPL Inc's future - a critical department is filled with chuds who do no work and play table tennis all day.
Cheeseburger is left with no choice but to lay off this entire department, but he must lay them off one-by-one due to system limitations. Additionally, each laid off employee will generate internet outrage by posting on Reddit and Hacker News based on the number of already-vacated desks contiguously to their left and right.
Cheeseburger is set on firing the employees in order of least productive to most productive. Calculate the total media outrage that will be generated so he can pay off his friendly Reddit executives to remove the posts.
Specifically, there are employees sitting in a single row, indexed from
to
. Each employee has a unique productivity score from
to
, and employees are fired in increasing order of productivity. When each employee is laid off, they will generate an integer media outrage number equal to the number of already-laid-off colleagues' seats connected to them.
Equivalently, if and
are the nearest still employed colleagues to the left and right of them (using
indexing, and
or
if there are none), the media outrage generated is
.
Report the total sum of these outrage scores for all layoffs, or maybe Director Cheeseburger will lay off your department next!
Input
The first line contains a single integer
, the number of workers in the department to be laid off.
The next line contains a space-separated permutation of length . Specifically, it contains
space-separated integers
, such that each integer
appears exactly once. This represents the productivity scores of each employee.
Output
Output the total media outrage generated as the sum of the scores defined above when laying off all department employees in increasing order of their productivity scores.
Example
Input 1
3
3 2 1
Output 1
3
Initially, when position is fired, no one has been laid off next to them so there is no outrage generated. Next, position
is next to the already-fired position
, so an outrage of
is generated. Finally, position
is fired, and they are next to both of the already-fired colleagues, so a score of
is added, resulting in the final
outrage value.
Input 2
4
2 4 1 3
Output 2
4
The first two layoffs result in outrage. The third results in
, as only the colleague to position
's left has been laid off at this point. Finally all
other employees have been laid off when the final employee is laid off. So
is the total score.
Input 3
5
1 3 2 5 4
Output 3
6
We ran out of budget to make this worked solution, apologies. We hope this image will placate you instead.

Input 4
7
1 7 3 5 2 4 6
Output 4
14
Comments
sybau