# Root of integer difference equation

I have a function f[k] where k is a nonnegative integer. My function f has a single point where it attains its maximum (though is not necessarily discrete-concave): it occurs at the first time when the difference f[k+1]-f[k]<=0. Is there a way I can ask Mathematica to solve for such a k? Ideally there would be a functional expression for the optimal k.

As a simple example, consider the problem of finding the index of the last positive element in a vector of sorted (descending) values. Is there a Mathematica function that I can use to solve something like Solve[DifferenceDelta[f[k], k] == 0]?

x := {10, 9, 6, 5, 2, 2, -1, -3, -4}
f[k] := Sum[x[i], {i, 1, k}]


In this specific case, I don't see a better way of identifying the optimal k besides evaluating each difference and checking its sign, so I don't expect Mathematica to provide an expression for the optimal k.

EDIT: to clarify, I am interested in approaches that will work for general f, not just this particular example.

• LengthWhile ? Commented Apr 21, 2023 at 18:36
• @imidak: thanks, i see how this would solve my particular example of f, but i am curious about code i can write to ask mathematica to return an expression like that for general f Commented Apr 21, 2023 at 18:41
• If you have some sort of upper bound on k, you can do something like Maximize[{f[k], Element[k, Integers] && 0 < k < kmax}, k] Commented Feb 16 at 11:22

This works when there are no duplicates:

Position[x,Last@Select[x, Positive]]

• thanks, i see how this would solve my particular example of f, but i am curious about code i can write to ask mathematica to return an expression like that for general f Commented Apr 21, 2023 at 19:02

Just to promote discussion:

Using  x := {10, 9, 6, 5, 2, 2, -1, -3, -4}

You can find position of maximum:

mx = Max[Accumulate@x]
Position[Accumulate@x, mx]


yields 34 and {{6}}

You could use Differences and FirstPosition

FirstPosition[Differences[Accumulate[x]], _?(# <= 0 &)]


yields {6}