返回介绍

solution / 0600-0699 / 0624.Maximum Distance in Arrays / README_EN

发布于 2024-06-17 01:03:36 字数 3606 浏览 0 评论 0 收藏 0

624. Maximum Distance in Arrays

中文文档

Description

You are given m arrays, where each array is sorted in ascending order.

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|.

Return _the maximum distance_.

 

Example 1:

Input: arrays = [[1,2,3],[4,5],[1,2,3]]
Output: 4
Explanation: 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.

Example 2:

Input: arrays = [[1],[1]]
Output: 0

 

Constraints:

  • m == arrays.length
  • 2 <= m <= 105
  • 1 <= arrays[i].length <= 500
  • -104 <= arrays[i][j] <= 104
  • arrays[i] is sorted in ascending order.
  • There will be at most 105 integers in all the arrays.

Solutions

Solution 1

class Solution:
  def maxDistance(self, arrays: List[List[int]]) -> int:
    ans = 0
    mi, mx = arrays[0][0], arrays[0][-1]
    for arr in arrays[1:]:
      a, b = abs(arr[0] - mx), abs(arr[-1] - mi)
      ans = max(ans, a, b)
      mi = min(mi, arr[0])
      mx = max(mx, arr[-1])
    return ans
class Solution {
  public int maxDistance(List<List<Integer>> arrays) {
    int ans = 0;
    int mi = arrays.get(0).get(0);
    int mx = arrays.get(0).get(arrays.get(0).size() - 1);
    for (int i = 1; i < arrays.size(); ++i) {
      var arr = arrays.get(i);
      int a = Math.abs(arr.get(0) - mx);
      int b = Math.abs(arr.get(arr.size() - 1) - mi);
      ans = Math.max(ans, Math.max(a, b));
      mi = Math.min(mi, arr.get(0));
      mx = Math.max(mx, arr.get(arr.size() - 1));
    }
    return ans;
  }
}
class Solution {
public:
  int maxDistance(vector<vector<int>>& arrays) {
    int ans = 0;
    int mi = arrays[0][0], mx = arrays[0][arrays[0].size() - 1];
    for (int i = 1; i < arrays.size(); ++i) {
      auto& arr = arrays[i];
      int a = abs(arr[0] - mx), b = abs(arr[arr.size() - 1] - mi);
      ans = max({ans, a, b});
      mi = min(mi, arr[0]);
      mx = max(mx, arr[arr.size() - 1]);
    }
    return ans;
  }
};
func maxDistance(arrays [][]int) (ans int) {
  mi, mx := arrays[0][0], arrays[0][len(arrays[0])-1]
  for _, arr := range arrays[1:] {
    a, b := abs(arr[0]-mx), abs(arr[len(arr)-1]-mi)
    ans = max(ans, max(a, b))
    mi = min(mi, arr[0])
    mx = max(mx, arr[len(arr)-1])
  }
  return ans
}

func abs(x int) int {
  if x < 0 {
    return -x
  }
  return x
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文