reduce runtime of problem_9 from O(n^3) to O(n^2)