DBLDROP - Editorial

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4

Author: raysh07
Tester: iceknight1093
Editorialist: iceknight1093

DIFFICULTY:

TBD

PREREQUISITES:

None

PROBLEM:

You’re given an array A.
You may choose at most one index i and replace A_i by 2\cdot A_i.

The score of the array is \text{sum}(A) - \max(A).
Find the maximum possible score after the operation.

EXPLANATION:

The constraints are low enough that the obvious \mathcal{O}(N^2) brute force will pass.
However, there is a better solution.

Let S = \text{sum}(A) and M = \max(A).
If we don’t perform the operation, the score is just S - M.

Otherwise, suppose we double A_i.
Then,

  • The sum increases by A_i, so it becomes S + A_i.
  • The new maximum is \max(M, 2A_i), since A_i is the only element that changed.

So, the score is S + A_i - \max(M, 2A_i).

There are only N choices of i, so just try all of them and take the best result.
This gives a linear time solution.

TIME COMPLEXITY:

\mathcal{O}(N) per testcase.

CODE:

Editorialist's code (PyPy3)
for _ in range(int(input())):
    n = int(input())
    a = list(map(int, input().split()))
    
    s, m = sum(a), max(a)
    ans = s - m
    for i in range(n):
        ans = max(ans, s + a[i] - max(m, 2*a[i]))
    print(ans)