Finding the maximum inclusive distance between two duplicate numbers in an array The prompt that made me put this function together was sourced from CodingBat.

I was curious about cleaner, more correct methods of doing putting this together such as finding a cleaner way to tell if there is or is not a duplicate in the array. I am also trying to be as efficient as possible. I believe this is an \$O(n^2)\$ function. Let me know what I should change.

The code works just fine. I just feel like there is quite a lot I can streamline and I would like to be pointed in the right direction.

 public int maxSpan(int[] nums) {
    int highestSpan = 0;
    int span;
    boolean duplicate = false;
    if (nums.length == 0)
        return highestSpan;
    for (int i = 0; i &lt; nums.length; i++) {
        for (int j = 0; j &lt; nums.length; j++){

            if ((nums[i] == nums[j])&amp;&amp; j != i){ //if duplicate
                duplicate = true;
                //get the absolute value of j - i
                span = j - i + 1; //Add 1 because it needs to count itself
                //if it is larger than the highestSpan then record it
                if (span &gt; highestSpan)
                    highestSpan = span;
            }
        }
    }
    if (duplicate)
        return highestSpan;
    else
        return 1;
}
Avoid unnecessary flag variables

The variable duplicate is unnecessary, because you could drive the same meaning from highestSpan &gt; 0. It's an extra hurdle to keep this flag, I suggest to drop it.

Improving the algorithm

I believe this can be solved in \$O(N)\$ time and space, by using a map to record the position of the first occurrences of numbers. If a number was seen already, check the distance and update the max distance if necessary. Otherwise record the current position.