Editorial for DMOPC '20 Contest 1 P3 - Victor's Algorithm


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: Kirito

Subtask 1

Let [S1,,Sk] be non-decreasing and let [Sk+1,,SN] be non-increasing.

For Si to be non-decreasing, we want SiSi+1. Thus we must add max(0,SiSi+1) to Si+1.

Similarly, for Si to be non-increasing, we want SiSi+1. Thus we must add max(0,Si+1Si) to Si.

Finally, either SkSk+1 or SkSk+1, so we are done.

Doing this by iterating the array for each value of k gives an O(N2) solution.

Time Complexity: O(N2)

Subtask 2

Note that if [S1,,Sk] is non-decreasing, then [S1,,Sk1] must also be non-decreasing. Thus we can precompute the amount of time it takes [S1,,Sk] to become non-decreasing for all k in O(N).

By the same argument, we can precompute the amount of time it takes [Sk,,SN] to become non-increasing for all k in O(N).

Iterating the array for each value of k again, we obtain an O(N) solution.

Time Complexity: O(N)

Alternate Solution

We present a greedy algorithm that solves the problem in O(N). We take advantage of the fact that it is never optimal to increment ak if ak=max(S).

  1. Find an index i such that Si=max(S).
  2. Now make [S1,,Si] non-decreasing and make [Si,,SN] non-increasing.

Note that both steps take O(N) time and thus the overall algorithm also takes O(N) time.

Time Complexity: O(N)


Comments

There are no comments at the moment.