Adding a c version, more appropiate for this problem.
The algoritms is O(n^2) in time complexity and O(1) in mem complexity.