Implementation
I'm missing your includes.
You seem to use using namespace std;
. Like most namespaces, std
is not designed for wholesale importation, and while there are symbols guaranteed to be declared under specific circumstances, there can be any number of additional ones, which can break your build or cause silent misbehavior.
int
only has a guaranteed maximum of \$2^{16}-1\$, but the answer can need just a bit less than \$2^{24}\$. long
seems more appropriate.
If you stop synchronizing with stdio, why don't you also untie input and output?
std::cin.tie(nullptr);
Manual flushing is nearly always just a waste. Use plain '\n'
, and flush with std::flush
where needed.
External input is generally unreliable, if not outright malicious. Either ask for an exception on error, or test manually.
Limit your variables to the smallest scope you can. This way, you can eliminate spurious initialization, and avoid having to keep it in mind when its value is no longer or not yet of any consequence.
return 0;
is implicit for main()
.
Algorithm
Your algorithm has a runtime complexity of \$\Theta(n^2)\$.
janos demonstrates in his answer how to get a linear algorithm, which is easy enough to adapt to streaming the input if wanted, getting rid of the storage for the sequence as well.
Simplified and adapted for streaming:
- Start with a best result of \$r = 0\$.
- Start with a best high candidate of \$high = -\infty\$.
- Start with a best low candidate of \$low = +\infty\$.
- Iterate over all elements of the sequence \$S\$ in order:
- Increment \$high\$, decrement \$low\$ to adjust for distance.
- If the current element is higher/lower, replace \$high\$/\$low\$.
- Update \$r\$ using the current element \$x\$ like this: \$r = \max(r, x - low, high - x)\$
Coding that up using the given limits:
long r = 0;
long low = std::numeric_limits<long>::max();
long high = std::numeric_limits<long>::min();
for (const auto x : S) {
low = std::min(low - 1, x);
high = std::max(high + 1, x);
r = std::max({r, x - low, high - x});
}
#include
andusing
lines. It can really help reviewers if they are able to compile and run your program. \$\endgroup\$O(n^2)
have you looked for an implementation that is more linear? \$\endgroup\$