An O(nlogn) approach to the solution.