An optimal approximation algorithm for Bayesian inference