Time to learn monotone stack.
Solution #
It’s quite obvious that the answer goes non-decreasing from the start and at some point turns to non-increasing. We want to find the optimal turning point.
We can build two arrays and of length n. The ith element of represents the maximum sum of floors from 1 to i if the floors are non-decreasing. Similar definition for . The turning point t is where is maximum.
For example: let
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
pre | 1 | 3 | 6 | 7 | 5 |
suf | 5 | 7 | 6 | 3 | 1 |
m | 1 | 2 | 3 | 2 | 1 |
pre+suf-m | 5 | 8 | 9 | 8 | 5 |
We can build the arrays by maintaining a mono-increasing stack stack<pair<ll,ll>>
to find the rightest number smaller than m_i
. The second element is the number of floors and first element is the number of buildings with the same height. You will understand it better in the detailed buildings process of :
i=0
nothing in the stack.
pre[0]+=1
Push{1,1}
to the stack and now the stack:{{1,1}}
i=1
First set pre[1]=pre[0]
Since m[1]>stack.top().second
, no pop.
pre[1]+=m[1]
now
Push {1,2} to the stack and the stack is now:{{1,1},{1,2}}
i=2
Similar to i=1.
pre[2]=6
{{1,1},{1,2},{1,3}}
i=3
m[3]<stack.top().second
which means that we need to change the height of previous buildings to keep the monotonicity. Keep popping out the bigger element and {1,3}
is popped. The pre[3]
should be decreased by 1*3 and is 3 now. Then the height of 2,3 should be 2 and pre[3]+=2*2
. Finally we push {2,2}
to the stack.
i=4
Similarly, we pop out {2,2}
and {1,2}
and pre[4]-=2*2+1*2
and now pre[4]=1
. Then the height of 1,2,3,4 should be 1 and pre[4]+=4*1
. Finally push {4,1}
to the stack.
We could build in the similar way but go from right to left.