We propose an algorithm to compute the optimal parameters of a probabilistic data propagation algorithm for wireless sensor networks (WSN). The probabilistic data propagation algorithm we consider was introduced in previous work, and it is known that this algorithm, when used with adequate parameters, balances the energy consumption and increases the lifespan of the WSN. However, we show that in the general case achieving energy balance may not be possible. We propose a centralized algorithm to compute the optimal parameters of the probabilistic data propagation algorithm, and prove that these parameters maximize the lifespan of the network even when it is not possible to achieve energy balance. Compared to previous work, our contribution is the following: (a) we give a formal definition of an optimal data propagation algorithm: an algorithm maximizing the lifespan of the network. (b) We find a simple necessary and sufficient condition for the data propagation algorithm to be optimal. (c) We constructively prove that there exists a choice of parameters optimizing the probabilistic data propagation algorithm. (d) We provide a centralized algorithm to compute these optimal parameters, thus enabling their use in a WSN. (e) We extend previous work by considering the energy consumption per sensor, instead of the consumption per slice, and propose a spreading technique to balance the energy among sensors of a same slice. The technique is numerically validated by simulating a WSN accomplishing a data monitoring task and propagating data using the probabilistic data propagation algorithm with optimal parameters.