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
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
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
If s_i=1, we update
Thus, every position is processed exactly once.
The overall time complexity is — .