a O(n^2) solution, TLE
a O(n) solution from discussion, accepted