Stochastic dynamics of resistive switching: fluctuations lead to optimal particle number