Dynamic programming with convexity, concavity and sparsity