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