Search for a command to run...
Progressive hints first, then the full explanation and implementation when you're ready to cash out.
Review status
AI-generated and still unreviewed. Double-check the details before internalizing them.
Hints
Open only as much as you need to keep the solve alive.
Every prefix maximum is at most the maximum element of the whole array. That gives a very obvious upper bound on the answer.
If the global maximum is , then the value of any arrangement can never exceed
Ask what happens if you put one occurrence of the global maximum at position .
With at the first position, every prefix already contains , so every prefix maximum is exactly .
One swap is enough: swap with any position containing the global maximum. If it is already first, do nothing. The answer is just . Yep, that's the whole damn trick.
Let .
For any array order, each prefix maximum is at most , because no element in the array is larger than the global maximum. Therefore the value is bounded by
So is the absolute best possible value.
Can we reach it? Yes. Pick any index where . If , do nothing. Otherwise, swap and .
After that, the array starts with , so every prefix contains . Since no element is bigger than , every prefix maximum is exactly :
Therefore the value becomes
Since is both an upper bound and achievable in at most one swap, it is the answer. No need for fancy swap simulation; that would be bringing a cannon to a spoon fight.
Edge cases:
Complexity: per test case, with extra memory.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void setIO() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
int main() {
setIO();
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int mx = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
mx = max(mx, x);
}
cout << 1LL * n * mx << '\n';
}
return 0;
}#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void setIO() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
int main() {
setIO();
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int mx = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
mx = max(mx, x);
}
cout << 1LL * n * mx << '\n';
}
return 0;
}