The solution is O(N)
and there is no need to perform any calculus, although it helps to understand the shape of the curve.
The answers above are doing the most intuitive thing and solving the equation to find the minimum or maximum and then splitting the list.
There is an advantage in calculating the first derivative but no need to actually do so, nor do we need to find the maximum or minimum point at this time.
Just know that it could move in one direction and then back in the other direction but will never change direction more than once.
We are going to start at each end and iterate across from both sides until we merge somewhere in the middle. Before we do anything else we need to check the direction at each end, which we will do by just comparing the end two elements. So we see if one end is moving upward and the other downward.
If we have N
elements let's say we have data X[0]
and X[N-1]
so calculate f(X[0])
and f(X[N-1])
and f(X[1])
and f(X[N-2])
. If f(X[0]) < f(X[1])
and f(X[N-1]) > f(X[N-2])
then actually all our data is one side of the maximum/minimum and thus already sorted. Same if the comparisons are in the other direction. (One direction may require a reverse).
Otherwise just perform the merge from both ends, thus f(X[0])
and f(X[N-1])
are either maxima or minima of their sub-ranges (we know from the earlier comparisons) and create the merged list from whichever is the appropriate direction.
Applying to your data:
-1 0 1 2 3 4
A = -1, B = 2, C = -1`
f = [ -4, -1, 0, -1, -4, -9 ]
-4 < -1
and -9 < -4
so we do cross the point and we have minima at each end.
-9 is lower than -4
-4 and -4 are equal so push both
-1 and -1 are equal so push both
0 remains.
our sequence is [-9, -4, -4, -1, -1, 0 ]