Maximum Sum#12782

Maximum Sum (Editorial)

Problem author:

Maryan Shyika

Prepared by:

Maryan Shyika

Tutorial:

Maryan Shyika

Idea

Notice that for a fixed index such that s_i=0, it is enough to know only one index j>i such that s_j=1 and the value a_j is as large as possible.

Indeed, once is fixed, the value a_i does not change, so in order to maximize

a_i+a_j

we should always choose the maximum possible a_j among all positions to the right for which s_j=1.

Therefore, we iterate through the array from right to left and maintain

mx=\max a_j

over all already processed positions such that s_j=1.

If at the current position we have s_i=0, then, provided that mx>a_i, we can update the answer with

a_i+mx.

If s_i=1, we update

mx=\max(mx,a_i).

Thus, every position is processed exactly once.

The overall time complexity is — .