<p>You are given <code>m</code> <code>arrays</code>, where each array is sorted in <strong>ascending order</strong>.</p>

<p>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 <code>a</code> and <code>b</code> to be their absolute difference <code>|a - b|</code>.</p>

<p>Return <em>the maximum distance</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

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

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> arrays = [[1],[1]]
<strong>Output:</strong> 0
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == arrays.length</code></li>
	<li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= arrays[i].length &lt;= 500</code></li>
	<li><code>-10<sup>4</sup> &lt;= arrays[i][j] &lt;= 10<sup>4</sup></code></li>
	<li><code>arrays[i]</code> is sorted in <strong>ascending order</strong>.</li>
	<li>There will be at most <code>10<sup>5</sup></code> integers in all the arrays.</li>
</ul>

"""
find the min value 
find the max value
return max value

dont peak values from the same array twice

[1,2,33]
[4,5]
[1,2,3]

all 1st elements into min heap
all last elements into max heap ?

(1, 1), (4, 2), (1, 3)
(-33, 1), (-5, 2), (-3, 3)

2 min elelnts from min heap
2 max elements from max heap




"""
class Solution:

    def maxDistance(self, arrays: List[List[int]]) -> int:
      min_h, max_h = [], []
      for i, arr in enumerate(arrays):
        min_h.append((arr[0], i))
        max_h.append((-arr[-1], i))

      heapq.heapify(min_h)
      heapq.heapify(max_h)

      #min pairs
      min_1, min_arr_1 = heapq.heappop(min_h)
      min_2, min_arr_2 = heapq.heappop(min_h)

      #max pairs
      max_1, max_arr_1 = heapq.heappop(max_h)
      max_2, max_arr_2 = heapq.heappop(max_h)

      res = []
      if min_arr_1 != max_arr_1:
        res.append(abs(max_1 + min_1))
      else:
        res.append(abs(max_2 + min_1))
        res.append(abs(max_1 + min_2))

      if min_arr_2 != max_arr_2:
        res.append(abs(max_2 + min_2))
      else:
        res.append(abs(max_1 + min_2))
        res.append(abs(max_2 + min_1))

      return max(res)
      

    #@ Time Limit Exceeded
    def maxDistance_(self, arrays: List[List[int]]) -> int:
      res = 0
      for i, arr_1 in enumerate(arrays):
        for j in range(i + 1, len(arrays)):
          res_1 = arrays[j][-1] - arr_1[0]
          res_2 = arr_1[-1] - arrays[j][0]
          res = max(res, res_1, res_2)

      return res
48034