Editorial for Circus 2
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Use two pointers, one at each end of the array.
At any step, the current pair of posts gives excitement factor
. Record that value, then move the pointer pointing to the shorter
post inward:
- if
, increment
;
- otherwise, decrement
.
Why is this safe? Suppose . Any pair that keeps the same left post
but moves the
right post inward has smaller distance, and its minimum height is still at most
. So no such
pair can beat the current one. That means the left pointer can be discarded safely.
Each pointer moves at most times, so the algorithm runs in
time.
Solution (Python)
n = int(input())
a = list(map(int, input().split()))
l = 0
r = n - 1
ans = 0
while l < r:
ans = max(ans, (r - l) * min(a[l], a[r]))
if a[l] <= a[r]:
l += 1
else:
r -= 1
print(ans)
Comments