leetcode624: Maximum Distance in Arrays

来源:互联网 发布:怎么查看网络是否稳定 编辑:程序博客网 时间:2024/06/06 02:56

Given m arrays, and each array is sorted in ascending order. Now you can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a-b|. Your task is to find the maximum distance.

Example 1:

Input: [[1,2,3], [4,5], [1,2,3]]Output: 4Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.

Note:

  1. Each given array will have at least 1 number. There will be at least two non-empty arrays.
  2. The total number of the integers in all the m arrays will be in the range of [2, 10000].
  3. The integers in the m arrays will be in the range of [-10000, 10000].
public int maxDistance(int[][] arrays) {int res = 0;int min = arrays[0][0];int max = arrays[0][arrays[0].length - 1];for (int i = 1; i < arrays.length; i++) {res = Math.max(res, Math.abs(arrays[i][arrays[i].length - 1] - min));res = Math.max(res, Math.abs(arrays[i][0] - max));max = Math.max(max, arrays[i][arrays[i].length - 1]);min = Math.min(min, arrays[i][0]);}return res;}