Average cost and optimization