Do three sweeps through the array. First, from j=2
up, filling the auxiliary array a
minimum element so far. Then drill down from top i=n-1
, filling (also top to bottom) another auxiliary array, b
, with the maximum element so far (top). Now sweep both auxiliary arrays, looking for the maximum difference b[i]-a[i]
.
That will be the answer. O(n)
as a whole. You can say that it is a dynamic programming algorithm.
edit:. As an optimization, you can eliminate the third sweep and the second array and find the answer in the second sweep, supporting two loop variables, max-so-far-from-the -top and max-difference.
As for the βpointersβ on how to solve such problems in general, you usually try to use some common methods, as you wrote, - share and win, memoization / dynamic programming, etc. First of all, carefully study your problems and concepts. Here it is maximum / minimum. Separate these concepts and see how these parts come together in the context of the problem, possibly changing the order in which they are calculated. Another is looking for hidden order / symmetry in your problem.
In particular, fixing an arbitrary interior point k
in the list, this problem reduces to finding the difference between the minimum element among all j
such that 1<j<=k
and the maximum element among i
s: k<=i<n
. You see here the separation and conquest, as well as the differentiation of the concepts max / min (i.e., their progressive calculation) and the interaction between the parts. A hidden order is displayed ( k
goes through the array), and memoization helps preserve intermediate results for max / min values.
Fixing an arbitrary point k
can be considered as solving a smaller sub-problem first ("for a given k
...") and finding out if there is something special in it, and it can be canceled - generalized - abstracted.
First, there is a method that allows you to first formulate and solve a big problem, so that the original problem is part of this larger one. Here we are thinking of finding all the differences for each k, and then finding the maximum of them.
The double use of intermediate results (used both in comparison for a particular point k
and in calculating the next intermediate result in each direction) usually means significant savings. So,
- divide and rule
- memoization / dynamic programing
- hidden order / symmetry
- separation of concepts - type of use of components
- dual use - locate dual use parts and save them.
- solution to a big problem
- attempt to arbitrary subtask and abstract on it