Solution (source code)

= Solution

Before the barrier has been hit, the two next-step continuation values are
$$
U_u=U(n,s(1+b))\mathbf1_{\{s(1+b)<B\}},
\qquad U_d=U(n,s(1+a)).
$$
The replicating stock holding on $(n-1,n]$ is therefore
$$
\Delta_n^{\rm UO}(s)=\frac{U_u-U_d}{s(b-a)}.
$$
The bank holding is chosen from current wealth $U(n-1,s)$ as before. If the barrier has already been hit, the claim and both holdings are zero. Backward induction proves replication of the up-and-out payout.