The crucial understanding is that this can be done in O (n) only if you keep track of where the potentially useful values are before you make sure they become usable.
Start with best_i = best_j = max_i = 0. The first two track the values of i and j for use in the solution. The next one will write the index with the highest factor for i, i.e. Where A[i] - i is the highest.
Let me call the X value for some values of i and j "X i, j " and start by writing our best solution so far ala X best = X <sub> 0,0sub>
The increment n along the array ...
when the value of at [n] gives a better "i" contribution for A[i] - i than max_i, updates max_i.
when using n , since the index "j" gives X max_i, n is greater than X best , best_i = max_i, best_j = n.
Discussion - why / how it works
j_random_hacker comment offers me a sketch of the proof, but honestly I don’t know where to start. I will try to explain as much as possible - if anyone has a better explanation, please chip ....
Repeating the problem: the largest X i, j , where j> = i. Given that we can set the initial X best X 0.0 , the problem is to know when to update it and why. Since we consider sequential indices in the array as potential values for j, we want to generate X i, j = n for some i (discussed later) for comparison with X best , but what do I value for use? Well, if any index from 0 to n is <= j, the restriction j> = i does not matter if we choose the best value i from the indexes we have already visited. We proceed from the best value of i, separating the i-related contribution to X from the j-related contribution - A[i] - i - therefore, in preparation for considering whether we have a new best solution with j = n, we must support the variable best_i too when we go.
The way to solve the problem
Whatever it costs - when I was groping for a solution, I wrote down on paper some imaginary contributions i and j that I could see, covering interesting cases ... where Ci and Cj are the contributions associated with using n like me and j, respectively sort of
n 0 1 2 3 4 Ci 4 2 8 3 1 Cj 12 4 3 5 9
You will notice that I did not choose the values where Ci could be A [i] - i, and Cj could be A [j] + j ... I could see that the resulting solution should work for any formulas, and that just made it difficult to capture interesting cases. So, what is an interesting case? When n = 2, the value of Ci is higher than everything that we saw in the earlier elements, but, given only the knowledge of these early elements, we still do not see a way to use it. This scenario is the only "big" complication of the problem. Why do we need a Cj value of at least 9, so Xbest improves, which happens when n = 4. If we found an even better Ci in [3], then of course we would like to use it. best_i, where this waiting expectation index is good enough - Cj.