[LeetCode] Maximum Distance in Arrays

624. Maximum Distance in Arrays

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int maxDistance(vector<vector<int>>& A) {
priority_queue<pair<int, int>> mi;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> ma;
for(int i = 0; i < A.size(); i++) {
mi.push({A[i][0], i});
ma.push({A[i].back(), i});
if(mi.size() > 2) mi.pop();
if(ma.size() > 2) ma.pop();
}
int res = 0;
auto [ma1, idx1] = ma.top(); ma.pop();
auto [ma2, idx2] = ma.top();
auto [mi1, iidx1] = mi.top(); mi.pop();
auto [mi2, iidx2] = mi.top();
if(idx1 != iidx1) res = max(res, abs(ma1-mi1));
if(idx1 != iidx2) res = max(res, abs(ma1-mi2));
if(idx2 != iidx1) res = max(res, abs(ma2-mi1));
if(idx2 != iidx2) res = max(res, abs(ma2-mi2));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/22/PS/LeetCode/maximum-distance-in-arrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.