Park the cart. Then watch Pontryagin do it faster.
A cart with a limited engine must stop exactly at the flag in the shortest possible time. Try it by hand, then see why the optimal driver only ever floors it, and switches direction at most once.
01Your turn
First watch the optimal driver, then try it yourself while a faint blue cart races you. The steps inside the card tell you what to press; the scores below the track compare your time with the best possible one.
02The model
Position $q$, velocity $v$, engine force $u$:
$$\dot q = v,\qquad \dot v = u,\qquad |u(t)|\le 1 .$$The goal is to reach $(q,v)=(0,0)$ in minimal time $T$.
03The Hamiltonian says: floor it
With costate $(p_1,p_2)$ the Hamiltonian is $H = p_1 v + p_2 u$. It is linear in $u$, so its maximum over $|u|\le 1$ sits at an end of the interval:
$$u^*(t) = \operatorname{sign} p_2(t).$$This is bang–bang control: full thrust one way or the other, never anything in between.
04At most one switch
$$\dot p_1 = -\frac{\partial H}{\partial q} = 0,\qquad \dot p_2 = -\frac{\partial H}{\partial v} = -p_1 .$$So $p_1$ is constant and $p_2$ is linear in $t$. A linear function changes sign at most once, and so does the optimal control.
05The switching curve
The arcs that reach the origin with $u=\pm1$ form the curve
$$q = -\tfrac12\, v\,|v| .$$Above it, push left; below it, push right; switch when you hit it. The minimal time is
$$T^*(q,v)=\begin{cases} v + 2\sqrt{q + v^2/2}, & q > -\tfrac12 v|v|,\\[2pt] -v + 2\sqrt{-q + v^2/2}, & q < -\tfrac12 v|v| .\end{cases}$$Check: from $(1,0)$, push left for 1 s and right for 1 s, so $T^*=2$. These are the numbers printed by 04_minimum_time.py.
Methods. The optimal motion is evaluated in closed form (a direct port of candidates() from the course script), so no time stepping crosses the switch. Your motion is integrated exactly for constant thrust over each animation frame.