With brute force (original algorithm is in comments)