[InterviewBit] N max pair combinations

N max pair combinations

  • Time : O(nlogn)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
struct PairHash {inline std::size_t operator()(const std::pair<int, int> &v) const { return v.first * 31 + v.second; }};
typedef unordered_set<pair<long long, long long>, PairHash> uspll;

vector<int> Solution::solve(vector<int> &A, vector<int> &B) {
sort(begin(A), end(A));
sort(begin(B), end(B));
vector<int> res;
priority_queue<array<int,3>> Q;
int n = A.size();
uspll us;
us.insert({n-1,n-1});
Q.push({A[n-1] + B[n-1], n-1, n-1});

while(res.size() < n) {
auto [sum, i, j] = Q.top(); Q.pop();
res.push_back(sum);
if(i - 1 >= 0 and !us.count({i-1,j})) {
us.insert({i-1,j});
Q.push({A[i-1] + B[j], i-1, j});
}
if(j - 1 >= 0 and !us.count({i,j-1})) {
us.insert({i,j-1});
Q.push({A[i] + B[j-1], i, j-1});
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/06/PS/interviewbit/n-max-pair-combinations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.