A hamiltonian approach to optimal stochastic resource allocation