bruteforce and optimal solution to problem 1