I tried to solve this using two pointers and could not pass some of the hidden tests (time limit exceeded). I would really appreacite if someone could suggest a more optimal approach.