Dynamic version of the algorithm (extremely inefficient)