Given 3 arrays A,B,C find three indices i,j,k such that the value of I = max((a-b),(b-c),(c-a)) is minimized.
- a = A[i]
- b = B[j]
- c = C[k]
This is one of those problems that you can accidentally head down a rabbit hole. Remember the KISS principle. Instead of trying to do an elegant solution, write a direct solution and then attempt optimize it if need be.
And a simple test:
The answer came out as:
5 Min from: A@i=19, B@j=24, C@k=24
Seeing the answer suggests that the maximum minimum difference between elements of two arrays is what you need to search for. Deducing this algorithm from the statement would be very difficult for most people, but once the first solution is done and tested, it can be seen easily. This would reduce the search time:
- from a.Length * b.Length * c.Length
- to a.Length* b.Length + a.Length*c.Length+ b.Length*c.length
If a,b,c are known to be sorted, then we can further improve performance to
- to (a.Length+ b.Length) + (a.Length+c.Length)+ (b.Length+c.length)
With a little more complex coding, you can half this again to:
- a.Length+ b.Length + c.Length