I doubt very much that this is the correct answer, but if I were given this problem at work, I would do a quick sort by sort type by value, and then by index. Then I will go through my ordered array and for each value I will take the first and last index. This will be the maximum distance of the candidate. Each time I came across a new value, I would compare it with my current maximum distance, and then save only the max. So the runtime will be
sort + walk = total N Log N + N = N Log N
Example: Values โโin an unordered array: 1,2,3,1,5,3,3,3
1,1,2,3,3,3,3,5 = Value 0,3,1,2,5,6,7,4 = Index
1 = max 3-0 = 3
2 = x
3 = max 7-2 = 5
Max 5
Remember that this is probably NOT the answer of the tutorial, but it still works in N Log N, so I would use it when working without any problems for anything under a million elements.
Do you find any other potential answers to the problem? How about ways to improve this?
source share