Optimizing a c# solution (algorithm) - C#