Initial version - probably correct but as it's O(n^2), it was not accepted.
Linear time version - accepted by Online Judge
Clean up accepted O(n) version