Official
C - Max Ai+Bj Editorial by en_translator
There are \(N^2\) combinations of \((i,j)\), so evaluating \(A_i+B_j\) for all pairs \((i,j)\) does not finish within the execution time limit.
Here, notice that \(\max_{1 \leq i,j \leq N} (A_i + B_j) = \max_{1 \leq i \leq N} A_i + \max_{1 \leq j \leq N} B_j\). One can find \(\max_{1 \leq i \leq N} A_i\) by scanning the elements of \(A\) in a total of \(O(N)\) time, and same applies to \(\max_{1 \leq j \leq N} B_j\). Therefore, the problem has been solved in a total of \(O(N)\) time.
Sample code (Python)
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
print(max(A) + max(B))
Sample code (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
int a = -1e9, b = -1e9;
for (int i = 0; i < N; ++i) {
int x;
cin >> x;
a = max(a, x);
}
for (int i = 0; i < N; ++i) {
int x;
cin >> x;
b = max(b, x);
}
cout << a + b << endl;
}
posted:
last update: