Optimizing Energy Systems using Dynamic Programming