Searching the same values in an array If I am not mistaken, this method has a complexity \$O(N^2)\$:

int[] exampleArray = { 4, 6, 2, 2, 6, 6, 1, 55, 55, 2, 5, 6, 90, 8, 8, 8, 10, 70 };
int k = GetMaximumCycle(exampleArray);

public static int GetMaximumCycle(int[] anArray)
{
   int length = anArray.Length;
   int result = 0;
   for (int i = 0; i &lt; length; i++)
   {
      for (int j = 0; j &lt; length; j++)
      {
          if (anArray[i] == anArray[j])
          {
             if (!(result &gt; Math.Abs(i - j)))                            
                 result = Math.Abs(i - j);
          }                    
      }                
   }
   return result;
}


I compare values and gets the maximum difference between items of array.
The result variable is 10. 

And if an input array is very large, this code works slowly. Is it possible to simplify the for loops or remove the second for loop to have a complexity of \$O(N)\$?
You can use a Dictionary&lt;int, int&gt; of positions of the first occurrence of each element value.
Next, iterating over all elements of the input array, you do:


If the positions[value] is empty, store the current index i in it: positions[value] = i.
Else, calculate the distance (or cycle length).
If this distance is greater than maximum, save it as a new maximum.


This algorithm has time complexity \$O(n)\$.

The code:

public static class CycleSearch
{
    public static int GetMaximumCycle(int[] array)
    {
        Dictionary&lt;int, int&gt; positions = new Dictionary&lt;int, int&gt;();

        int result = 0;
        for (int i = 0; i &lt; array.Length; i++)
        {
            int value = array[i];
            int position;
            if (!positions.TryGetValue(value, out position))
            {
                positions[value] = i;
            }
            else
            {
                int cycleLength = i - position;
                if (cycleLength &gt; result)
                {
                    result = cycleLength;
                }
            }
        }
        return result;
    }
}


Usage:

int[] exampleArray = { 4, 6, 2, 2, 6, 6, 1, 55, 55, 2, 5, 6, 90, 8, 8, 8, 10, 70 };
Console.WriteLine(CycleSearch.GetMaximumCycle(exampleArray));


Output:


  10