Greedy heuristic working perfectly in O(nlogn) time