Solution (source code)

= Solution

Write $h_i=\mathbb E_i[J]=i/k$ and $v_i=\mathbb E_i[JX]$. Since $0\leq JX\leq X$, the latter <expected value> is finite. Conditional on the first move to $i-1$ or $i+1$, total time is one plus the remaining time, while the terminal success <indicator random variable> is unchanged. The <Markov property> and <linearity of expectation> give
$$
v_i=\tfrac12(v_{i-1}+h_{i-1})+\tfrac12(v_{i+1}+h_{i+1})
=\tfrac12v_{i-1}+\tfrac12v_{i+1}+\frac ik.
$$
At either absorbing boundary the remaining time is zero, so $v_0=v_k=0$.

Let $w_i=i(k^2-i^2)/(3k)$. The linear term has zero second difference and $i^3$ has second difference $6i$. Consequently
$$
w_{i+1}-2w_i+w_{i-1}=-\frac{2i}{k},
$$
which is exactly the required recurrence, and $w_0=w_k=0$. Uniqueness follows as before: the difference of two solutions has zero second difference and zero endpoint values. Hence
$$
\boxed{\mathbb E_i[Y]=v_i=\frac{i(k^2-i^2)}{3k}.}
$$
This is the success-weighted duration underlying the <duration of gambler's ruin conditioned on a chosen boundary>.