Editorial for Circus 2
Use this editorial only when stuck, and do not 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.
Approach
Use two pointers, one at each end of the array.
At any step, the current pair of posts gives excitement factor (r−l)⋅min(al,ar). Record that value, then move the pointer pointing to the shorter post inward:
- if al≤ar, increment l;
- otherwise, decrement r.
Why is this safe? Suppose al≤ar. Any pair that keeps the same left post l but moves the right post inward has smaller distance, and its minimum height is still at most al. So no such pair can beat the current one. That means the left pointer can be discarded safely.
Each pointer moves at most n times, so the algorithm runs in O(n) 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)
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.