The idea as we go through the arrays we keep max and min values we have seen. With those we can then test the distance with the beginning and the end of the current array.

```
public int maxDistance(int[][] arrays) {
int m = arrays.length;
if (m < 2) {
return 0;
}
int min = arrays[0][0];
int max = arrays[0][arrays[0].length-1];
int res = Integer.MIN_VALUE;
for (int i = 1; i < m; i++) {
int[] curr = arrays[i];
res = Math.max(res, Math.abs(curr[0] - max));
res = Math.max(res, Math.abs(curr[curr.length -1] - min));
min = Math.min(min, curr[0]);
max = Math.max(max, curr[curr.length-1]);
}
return res;
}
```