First approach to solve problem 3. Too slow.