finished dynamic algorithm