using brute force to solve it, with complexity O(n^2), but there is a more decent algorithm with O(n), cannot figure out why