Official

F - Buy Balls Editorial by en_translator


First of all, sort each of \(A\) and \(B\) in descending order. Then, the maximum sum is always achieved by taking some leading elements of \(A\), and some leading elements of \(B\).

Let \(\displaystyle S_i=\sum_{j=1}^i A_i\) and \(T_i=\sum_{j=1}^iB_j\), with \(S_0=0\) and \(T_0=0\). The sought answer is the maximum \(S_i+T_j\) among \(0\leq i\leq N, 0\leq j\leq M, j\leq i\), but evaluating it for all \((i,j)\) costs \(O(NM)\) time, which does not finish within the time limit.

Let us fix \(i\) and consider when \(S_i+T_j\) is maximized. Since \(j\) can take any value within \(0\leq j\leq \min(i,M)\), it is sufficient to use the maximum value among \(T_0,T_1,\ldots,T_{\min(i,M)}\). This can be done in \(O(1)\) time by precalculating the cumulative max of \(T\) in \(O(M)\) time.

The computational complexity is \(O(N\log N + M\log M)\), where the sorting is the bottleneck.

N, M = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
A.sort(reverse=True)
B.sort(reverse=True)
S, T, maxT = [0] * (N + 1), [0] * (M + 1), [0] * (M + 1)
for i in range(N):
    S[i + 1] = S[i] + A[i]
for i in range(M):
    T[i + 1] = T[i] + B[i]
    maxT[i + 1] = max(maxT[i], T[i + 1])

ans = 0
for i in range(N + 1):
    ans = max(ans, S[i] + maxT[min(i, M)])
print(ans)

posted:
last update: