Time limit exceeded for large-size input. Current solution is O(n ^ 2).
Still looking for O(n lg n) solutions, possibly with sorting?