LeetCode Solutions

624. Maximum Distance in Arrays

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  int maxDistance(vector<vector<int>>& arrays) {
    int ans = 0;
    int min = 10000;
    int max = -10000;

    for (const vector<int>& A : arrays) {
      ans = std::max({ans, A.back() - min, max - A.front()});
      min = std::min(min, A.front());
      max = std::max(max, A.back());
    }

    return ans;
  }
};
			

class Solution {
  public int maxDistance(List<List<Integer>> arrays) {
    int ans = 0;
    int min = 10000;
    int max = -10000;

    for (List<Integer> A : arrays) {
      ans = Math.max(ans, Math.max(A.get(A.size() - 1) - min, max - A.get(0)));
      min = Math.min(min, A.get(0));
      max = Math.max(max, A.get(A.size() - 1));
    }

    return ans;
  }
}
			

class Solution:
  def maxDistance(self, arrays: List[List[int]]) -> int:
    ans = 0
    mini = 10000
    maxi = -10000

    for A in arrays:
      ans = max(ans, A[-1] - mini, maxi - A[0])
      mini = min(mini, A[0])
      maxi = max(maxi, A[-1])

    return ans