Faster version. Still TLE for large data.