I came up with an O(N^2) solution but the program was only able to pass about half of the test cases due to the program not being fast enough. I receieved a rejection today, hopefully someone can benefit from this.