# Maximum Distance in Array

• Please double check solution 3. It seems incorrect.

• @zestypanda Thanks for pointing it out. I have removed #3 approach.

• I didn't quite understand the 3rd approach . help??

• @dimessi I've updated the description in the 3rd approach. Hope it'll be clear now.

• How it works, if min and max is in same list

• @Ryanm In that case also, the distance calculation isn't max-min, but it is MAX(max-a[0], a[n-1]-min). Here a[0] and a[n-1] belong to the next array being considered. Thus, the distance is always calculated among separate arrays only. You can see the illustration above which includes this case as well.

• For approach 2, shouldn't the outer for loop run for (length-1) times? thx

• @RSLeet2017 Yes. I have updated the code. Thanks

• seems to be a typo in #3 ?
a[n−1]−b[0] and b[m-1]-b[0] should be a[n−1]−b[0] and b[m-1]-b[0]b[m−1]−a[0]

• @venkat I have corrected it. Thanks.

• The third solution is really brilliant!

• @vinod23 3rd approach is awesome.

• you don't have to recompute res for each iteration in the 3rd solution, just at the end once you have min and max vals.

• In the third solution you need to check if the array[i] is empty or not.
For example, an array like this: array = {{1,2,3}, {4,5} , {1,2,3} , {}}.

Also needed to check if array is empty or not.
For example, an array like this: array = {{}}.

I corrected the code as below:

``````public static int maxDistance (int [][] arrays){
int j=0;
for (j=0; j<arrays.length && arrays[j].length ==0;j++);
if (j == arrays.length){
return 0;
}
int res = 0;
int min = arrays[0][0];
int max = arrays[0][arrays[0].length-1];

for (int i=j; i<arrays.length; i++){
if (arrays[i].length == 0){
continue;
}
res = Math.max(res , Math.abs(arrays[i][arrays[i].length-1] - min));
res = Math.max(res , Math.abs((max - arrays[i][0])));

min = Math.min(min , arrays[i][0]);
max = Math.max(max , arrays[i][arrays[i].length-1]);
}
return res;
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.