PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: munch_01
Tester: sushil2006
Editorialist: iceknight1093
DIFFICULTY:
Simple
PREREQUISITES:
None
PROBLEM:
Given an array A, find the maximum possible value of A_i \bmod (A_j + A_k) across all triplets (i, j, k) of pairwise distinct indices.
EXPLANATION:
A simple first observation is to note that A_i \bmod (A_j + A_k) can never be greater than A_i.
Either it will equal A_i itself (if A_j + A_k \gt A_i), or it will be something smaller than A_i.
This seems obvious, but is actually quite helpful - it tells us that if we fix the index i, no matter what we choose for j and k, we cannot obtain a result larger than A_i itself.
It’s now not hard to see that in almost every case, for a fixed i it’s possible to obtain A_i by choosing j and k appropriately.
To see why, let’s first sort the array for convenience, so that A_1 \leq A_2 \leq\ldots\leq A_N. This doesn’t change the answer.
Now, for any i \lt N, we can choose j = N and k to be anything (other than i or N) - the sum A_N + A_k will definitely be larger than A_i because A_N is the largest element, so we’ll always have A_i \bmod (A_N + A_k) = A_i, as we wanted.
So, among all the choices of i \lt N, the best we can do is just A_{N-1}, i.e. the second maximum element of the array.
This leaves the case of i = N.
However, here we can use the constraint of N \leq 5000, and simply iterate through all pairs of j and k to compute the maximum possible value of A_N \bmod (A_j + A_k).
TIME COMPLEXITY:
\mathcal{O}(N^2) per testcase.
CODE:
Editorialist's code (PyPy3)
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
a.sort()
ans = a[-2]
for i in range(n-1):
for j in range(i+1, n-1):
ans = max(ans, a[-1] % (a[i] + a[j]))
print(ans)