Improved version. Passes all the test cases, however, it is too slow when N is large  (>5k) and times out. Must improve this.