1
$\begingroup$

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.

$\endgroup$
3
  • $\begingroup$ LengthWhile ? $\endgroup$
    – imida k
    Commented Apr 21, 2023 at 18:36
  • $\begingroup$ @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 $\endgroup$
    – rrrrr
    Commented Apr 21, 2023 at 18:41
  • $\begingroup$ 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] $\endgroup$ Commented Feb 16 at 11:22

2 Answers 2

1
$\begingroup$

This works when there are no duplicates:

Position[x,Last@Select[x, Positive]]
$\endgroup$
1
  • $\begingroup$ 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 $\endgroup$
    – rrrrr
    Commented Apr 21, 2023 at 19:02
1
$\begingroup$

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}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.