This problem is solved using the theory of optimal stopping
for Markov chains. I will explain some of the theory, then turn to your specific question. You can learn more about this fascinating topic in Chapter 4 of Introduction to Stochastic Processes by Gregory F. Lawler.
Think of a Markov chain with state space $\cal S$ as a game.
A payoff function
$f:{\cal S}\to[0,\infty)$
assigns a monetary "payoff'' to each state of the Markov chain.
This is the amount you would collect if you stop playing with the
chain in that state.
In contrast, the value function
$v:{\cal S}\to[0,\infty)$
is defined as the greatest expected payoff possible from each starting point;
$$v(x)=\sup_T \mathbb{E}_x(f(X_T)).$$ There is a single optimal strategy $T_{\rm opt}$
so that $v(x)=\mathbb{E}_x(f(X_{T_{\rm opt}})).$
It can be described as $T_{\rm opt}:=\inf(n\geq 0: X_n\in{\cal E})$,
where ${\cal E}=\{x\in {\cal S}\mid f(x)=v(x)\}$. That is, you should stop playing as soon as you hit the set $\cal E$.
Example:
You roll an ordinary die with outcomes $1,2,3,4,5,6$.
You can keep the value or roll again.
If you roll, you can keep the new value or roll a third time.
After the third roll you must stop. You win the amount showing on the die.
What is the value of this game?
Solution:
The state space for the Markov chain is
$${\cal S}=\{\mbox{Start}\}\cup\left\{(n,d): n=2,1,0; d=1,2,3,4,5,6\right\}.$$
The variable $n$ tells you how many rolls you have left, and this decreases by one every
time you roll. Note that the states with $n=0$ are absorbing.
You can think of the state space as a tree,
the chain moves forward along the tree until it reaches the end.

The function $v$ is given above in green, while $f$ is in red.
The payoff function $f$ is zero at the start, and otherwise equals the number of spots on $d$.
To find the value function $v$, let's start at the right hand side of the tree.
At $n=0$, we have $v(0,d)=d$, and we calculate $v$ elsewhere by working backwards,
averaging over the next roll and taking the maximum of that and the current payoff.
Mathematically, we use the property $v(x)=\max(f(x),(Pv)(x))$ where $Pv(x)=\sum_{y\in {\cal S}} p(x,y)v(y).$
The value of the game at the start is \$4.66. The optimal strategy is to keep playing
until you reach a state where the red number and green number are the same.