Finally solved this little fella O(2(N^2)logN)